首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于金字塔web框架错误,CSRF令牌丢失或无效

问关于金字塔web框架错误,CSRF令牌丢失或无效
EN

Stack Overflow用户
提问于 2013-07-23 16:56:17
回答 1查看 818关注 0票数 1

1.jinsa2模板文件:

代码语言:javascript
复制
<!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文件

代码语言:javascript
复制
@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文件:

代码语言:javascript
复制
    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禁止访问此资源被拒绝。CSRF令牌丢失或无效

如何解决这个问题?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-02 15:02:14

金字塔html post方法需要csrf_token,所以我需要:

查看:

代码语言:javascript
复制
csrf_token = request.session.get_csrf_token()
return {'csrf_token':csrf_token}

模板(Jinja2):

代码语言:javascript
复制
<input id="_csrf" type="hidden" value="{{ csrf_token }}"/>

成功~

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17805660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档