Flask中request获取请求参数再次拼接时,提示在请求上下文之外工作,请帮忙看看?
请路过大佬帮忙看看。
背景:我需要请求leancloud的数据库,前端上每次会分页请求,因此URL上有参数;直接前端请求,会带上数据库的id和key,我不想泄漏。
我想在前端请求云函数里的api接口,api中识别前端带上的参数,拼接成一个新的URL,由服务端去请求leancloud。初学前端知识,请不吝赐教。源代码如下:
# -*- coding: utf-8 -*-# @Author : GuoLe
# @Date : 2022/9/24 15:53
import json
import os
import requests
import flask
from flask import request
from http.server import BaseHTTPRequestHandler
app = flask.Flask(__name__)
@app.route('/bbtalk', methods=['GET','POST'])
def get_data():
skip = request.args.get('skip')
limit = request.args.get('limit')
count = request.args.get('count')
if skip :
if count :
url = 'https://leancloud.guole.fun/1.1/classes/content' + '?where=%7B%7D&limit=' + limit + '&skip=' + skip + '&order=-createdAt' + 'count=' + count
else :
url = 'https://leancloud.guole.fun/1.1/classes/content' + '?where=%7B%7D&limit=' + limit + '&skip=' + skip + '&order=-createdAt'
else :
if count :
url = 'https://leancloud.guole.fun/1.1/classes/content' + '?where=%7B%7D&limit=' + limit + '&order=-createdAt' + 'count=' + count
else :
url = 'https://leancloud.guole.fun/1.1/classes/content' + '?where=%7B%7D&limit=' + limit + '&order=-createdAt'
print(url);
data = []
header = {'X-LC-Id':os.environ["LEANCLOUD_APPID"],'X-LC-Key':os.environ["LEANCLOUD_APPKEY"],'Content-Type':'text/html;charset=utf-8'}
response = requests.get(url,headers=header)
data = response.content
print(data);
return data
class handler(BaseHTTPRequestHandler):
def do_GET(self):
data = get_data()
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data).encode('utf-8'))
return
if __name__ == '__main__':
# app.run(port=5000,debug=True)
print(get_data())
回答:
@app.route('/bbtalk', methods=['GET','POST'])
def get_data():
# 看这里, request这个是线程级http请求全局变量, 在Flask收到请求时, 会设置当前HTTP请求的参数
# 如果要在非HTTP请求外使用, 必需使用 `with app.test_request_context()` 包裹函数调用
skip = request.args.get('skip')
limit = request.args.get('limit')
count = request.args.get('count')
if __name__ == '__main__':
# app.run(port=5000,debug=True)
# 改这儿
with app.test_request_context(path='/请求路径', query_string='a=b&c=d'):
print(get_data())
以上是 Flask中request获取请求参数再次拼接时,提示在请求上下文之外工作,请帮忙看看? 的全部内容, 来源链接: utcz.com/p/938655.html