django - htaccess 在 heroku 上用于 django 应用程序

标签 django .htaccess heroku

标题几乎总结了我的问题。我想用密码保护我的 django 应用程序中的一些文件,这些文件位于 heroku 上。
如果我不能使用 htaccess,是否有人对我可以使用的其他内容有任何建议?
谢谢。

最佳答案

正如@mipadi 所说,您不能在 Heroku 上使用 htaccess,但您可以为此创建一个中间件:

from django.conf import settings
from django.http import HttpResponse
from django.utils.translation import ugettext as _


def basic_challenge(realm=None):
    if realm is None:
        realm = getattr(settings, 'WWW_AUTHENTICATION_REALM', _('Restricted Access'))
    # TODO: Make a nice template for a 401 message?
    response =  HttpResponse(_('Authorization Required'), mimetype="text/plain")
    response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
    response.status_code = 401
    return response

def basic_authenticate(authentication):
    # Taken from paste.auth
    (authmeth, auth) = authentication.split(' ',1)
    if 'basic' != authmeth.lower():
        return None
    auth = auth.strip().decode('base64')
    username, password = auth.split(':',1)
    AUTHENTICATION_USERNAME = getattr(settings, 'BASIC_WWW_AUTHENTICATION_USERNAME')
    AUTHENTICATION_PASSWORD = getattr(settings, 'BASIC_WWW_AUTHENTICATION_PASSWORD')
    return username == AUTHENTICATION_USERNAME and password == AUTHENTICATION_PASSWORD

class BasicAuthenticationMiddleware(object):
    def process_request(self, request):
        if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
            return
        if 'HTTP_AUTHORIZATION' not in request.META:
            return basic_challenge()
        authenticated = basic_authenticate(request.META['HTTP_AUTHORIZATION'])
        if authenticated:
            return
        return basic_challenge()

那么你需要在settings.py中定义:
BASIC_WWW_AUTHENTICATION_USERNAME = "your user"
BASIC_WWW_AUTHENTICATION_PASSWORD = "your pass"
BASIC_WWW_AUTHENTICATION = True

关于django - htaccess 在 heroku 上用于 django 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9399835/

相关文章:

python - 如何使用 Django/Python 在 SQLite 中存储获取的 JSON 数据

regex - urlrewrite 中 $1 之后的数字

php - Laravel url 显示未找到错误

wordpress - 将WordPress切换为https后重定向过多

python - 如何转储 request.POST 到 dict,维护多个值字段?

python - Django - 获取相关 key 并插入数据库

python - 基于 django 类的 View 不接受 view_args 和 view kwargs

postgresql - Heroku 页面 :backups fails with "an error"

ruby-on-rails - 在heroku上运行rails应用程序,在/public文件夹中看不到静态页面

mysql - Cygwin 上的 Heroku 正在记录一些奇怪的东西,看起来像 "mysql --help"