1
1.jinja2模板文件:關於金字塔的Web框架的錯誤,CSRF令牌丟失或無效
<!DOCTYPE html>
<html>
<head>
<title>image upload demo</title>
</head>
<body>
<form action="{{ imgup_url }}" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<input type=hidden id="token" value="{{ token }}">
<label for="filename">File:</label>
<input id="pictitle" name="pictitle" type="text" value="okkk" />
<input id="upfile" name="upfile" type="file" value="" />
<input id="button" type="submit" value="upload" />
</form>
</body>
</html>
2.views.py文件
@view_config(permission='post', route_name='imgup',
renderer='shootout:jinja2/imgup.jinja2',
check_csrf=False)
def ueditor_ImgUp(request):
""" upload image """
form = Form(request, schema=ImgUpSchema)
token1 = request.session.new_csrf_token()
if 'form.submitted' in request.params:
token2 = request.session.get_csrf_token()
if token2 != request.POST['csrf_token']:
raise ValueError('CSRF token did not match')
print "imgup is login begin!!!"
source_pictitle = request.POST.get('pictitle')
source_filename = request.POST['upfile'].filename
response = Response()
myresponse = __myuploadfile(fileObj, source_pictitle, source_filename, 'pic')
response.write(myresponse)
print "imgup is success!!!"
return response
else:
return {'imgup_url':'/imgup','token':token1}
3.__init__.py文件:
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
session_factory = UnencryptedCookieSessionFactoryConfig(
settings['session.secret']
)
authn_policy = SessionAuthenticationPolicy()
authz_policy = ACLAuthorizationPolicy()
config = Configurator(
settings=settings,
root_factory=RootFactory,
authentication_policy=authn_policy,
authorization_policy=authz_policy,
session_factory=session_factory
)
config.add_static_view('static', 'shootout:static')
config.add_static_view('html', 'shootout:html')
config.include(addroutes)
config.add_route('imgup','/imgup')
當提交上傳按鈕顯示: 403禁止 訪問被拒絕此re資源。 CSRF令牌丟失或無效
如何解決此問題?謝謝。
我沒有看到你的'CSRF令牌在你報告的消息中不匹配'錯誤,因此它不會在那裏發生,而是在你沒有粘貼的代碼中。鑑於這是一個403,它必須在你的授權設置的某些部分搜索'post'權限。無論如何,你還沒有粘貼足夠的代碼來診斷問題。 –
對於代碼的這些部分,我添加了一段代碼插件'\ _ \ _ init \ _ \ _。py',來看看。 –
對不起,我之前想要問的是:在代碼中的哪個位置響應csrf標記缺失而引發403響應?金字塔本身並不這樣做,所以它一定是你添加的東西。 –