Home  >  Q&A  >  body text

python - tornado开启了xsrf_cookies,在ckeditor中上传文件如何传入xsrf_form_html()?

tornado在setting中设置了"xsrf_cookies" : True,则需要在表单中添加{% module xsrf_form_html() %}。
但ckeditor如何传xsrf_cookies这个值,每次上传图片都显示'_xsrf' argument missing from POST。
如果把"xsrf_cookies"设置为False则上传成功。

下面是上传的代码


class ckuploadHandeler(BaseHandler):
    @authenticated
    def gen_rnd_filename(self):
        filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))



    @authenticated
    def post(self):

        """CKEditor file upload"""
        error = ''
        url = ''
        callback = self.get_argument("CKEditorFuncNum")

        if self.request.method == 'POST' and 'upload' in self.request.files:
            fileobj = self.request.files['upload']

            fname, fext = os.path.splitext(fileobj[0]['filename'])
            rnd_name = '%s%s' % (self.gen_rnd_filename(), fext)
            filepath = os.path.join(self.settings['static_path'], 'upload', rnd_name)
            # 检查路径是否存在,不存在则创建
            dirname = os.path.dirname(filepath)
            if not os.path.exists(dirname):
                try:
                    os.makedirs(dirname)
                except:
                    error = 'ERROR_CREATE_DIR'

            elif not os.access(dirname, os.W_OK):
                error = 'ERROR_DIR_NOT_WRITEABLE'
            if not error:
                print(filepath)
                with open(filepath,'wb') as up:      #有些文件需要已二进制的形式存储,实际中可以更改
                    up.write(fileobj[0]['body'])
                urlpath = filename='%s/%s' % ('upload', rnd_name)
                url = self.static_url(urlpath)
                print(url)
        else:
            error = 'post error'
        res = """
        <script type="text/javascript">
        window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
        </script>
        """ % (callback, url, error)
        self.write(res)
       

Handler的URL (r'/upload/', ckuploadHandeler),

显示错误`WARNING:tornado.general:403 POST /upload/?CKEditor=context&CKEditorFuncNum=1&langCode=zh (127.0.0.1): '_xsrf' argument missing from POST
`

如何在上传图片的时候把xsrf_cookies也post过去?

html代码:


<p class="field-box">
<textarea name="context" class="span12 " type="text" rows="9" required></textarea>

<script>
CKEDITOR.replace('context');
</script>
迷茫迷茫2742 days ago1004

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:44:12

    You can choose to override the check_xsrf_cookie() method and not check the upload request
    I just looked at the source code of tornado, you just need to do thischeck_xsrf_cookie() 方法,对上传这个请求不做检查
    我刚才看了下tornado的源代码,你只要这么做就行

    修改ckeditor.js的源代码,找到 <form enctype="multipart/form-data" method="POST" ...

    Modify the source code of ckeditor.js, find the line <form enctype="multipart/form-data" method="POST" ... (find it by searching) and edit it Generate the form code, add an input, type=hidden, value is to take the _xsrf value from the cookie) and that's it.

    In html, you still need to write {% module xsrf_form_html() %} (in the source code of tornado, executing xsrf_form_html() will call set_cookie('_xsrf')), so that there will be _xsrf value in the cookie Yes, just bring it up using the method mentioned above.

    js gets cookie code (taken from tornado documentation):

    function getCookie(name) {
        var r = document.cookie.match("\b" + name + "=([^;]*)\b");
        return r ? r[1] : undefined;
    }
    🎜PS: I am also a tornado fan. I have practiced the above method and it is feasible. 🎜

    reply
    0
  • Cancelreply