如何在Google App Engine上使用bcrypt?

4 投票
1 回答
2831 浏览
提问于 2025-04-18 05:28

我找到一个适用于Python的bcrypt库,看起来非常好用:

我在本地机器上安装了它,并测试了一个简单的示例,一切都正常:

>>> import bcrypt
>>> password = b"super secret password"
>>> # Hash a password for the first time, with a certain number of rounds
>>> hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))
>>> # Check that a unhashed password matches one that has previously been
>>> #   hashed
>>> if bcrypt.hashpw(password, hashed) == hashed:
...     print("It Matches!")
... else:
...     print("It Does not Match :(")

但是,在我的GAE应用中,当我使用 import bcrypt 时,出现了一个错误:

Traceback (most recent call last):
  File "/home/pedro/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/home/pedro/google_appengine/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/home/pedro/google_appengine/google/appengine/runtime/wsgi.py", line 84, in LoadObject
    obj = __import__(path[0])
  File "/home/pedro/google_appengine/hw4/blog.py", line 8, in <module>
    import bcrypt
ImportError: No module named bcrypt
INFO     2014-05-05 21:17:04,375 module.py:639] default: "GET /blog/signup HTTP/1.1" 500 -

这让我觉得我需要修改 app.yaml 文件,把这个库加进去:

application: calm-grid-571
version: 1
runtime: python27
api_version: 1
threadsafe: False

handlers:
- url: /static
  static_dir: static

- url: /.*
  script: blog.app

libraries:
- name: jinja2
  version: latest

- name: PIL
  version: latest

不过,当我查看官方支持的库页面时,找不到关于bcrypt的任何信息。

那么,我该如何在GAE中使用bcrypt库呢?这可能吗?

1 个回答

6

你需要把bcrypt这个库(或者其他任何非内嵌的库)放到你的项目里。建议在项目的根目录下创建一个libs文件夹(和app.yaml文件在同一个层级),然后把你需要的库的源代码放到这个文件夹里。

在这种情况下,最终的结果应该是这样:/libs/bcrypt/

确保在你想让代码把这个文件夹当作一个包的任何新文件夹里放一个空的__init__.py文件。之后,你只需要这样导入这个模块:from libs.bcrypt import bcrypt

补充说明:你也可以在你的应用引擎项目中只使用纯Python代码。可以试试py-bcrypt,它在App Engine上运行得很好。

撰写回答