标题几乎总结了我的问题。我想用密码保护我的 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/