gpt4 book ai didi

javascript - 将 CKeditor 集成到 Flask 时 CSRF 验证失败

转载 作者:行者123 更新时间:2023-12-03 10:19:10 24 4
gpt4 key购买 nike

我正在将 CKeditor 集成到 Flask 以添加富文本支持。但是当开启文件上传功能后,post请求总是失败。应该是csrf的问题。直接添加 {{csrf_token()} 不起作用。 CKeditor中有什么地方需要修改来添加csrf吗?

{% block content %}
<h1>Add articile:</h1>
<form>
<input type="hidden" name="csrf_token" value="{{csrf_token()}}" />
<textarea name="editor1" id="editor1" rows="20" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script type="text/javascript">
CKEDITOR.replace('editor1', {
filebrowserUploadUrl: '/ckupload',
});
</script>
</form>
{% endblock %}

处理文件上传,

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

@app.route('/ckupload', methods=['POST', 'OPTIONS'])
def ckupload():
"""CKEditor file upload"""
error = ''
url = ''
callback = request.args.get("CKEditorFuncNum")
print callback
print request.method
if request.method == 'POST' and 'upload' in request.files:
fileobj = request.files['upload']
fname, fext = os.path.splitext(fileobj.filename)
rnd_name = '%s%s' % (gen_rnd_filename(), fext)
filepath = os.path.join(app.static_folder, '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:
fileobj.save(filepath)
url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
else:
error = 'post error'
res = """<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)
response = make_response(res)
response.headers["Content-Type"] = "text/html"
return response

最佳答案

当前我的解决方法是向此网址添加 csrf 异常(exception)。

@csrf.exempt

关于javascript - 将 CKeditor 集成到 Flask 时 CSRF 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29721223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com