如何将url作为REST GET参数传递到FLASK中

2024-10-02 22:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码

from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
app.config['DEBUG'] = True
api = Api(app)

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app


class Default(Resource):
   def get(self, name):
    """Renders a sample page."""
    return "Hello " + name

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url

    # data = request.get(url)
    # return data

api.add_resource(Default, '/default/<string:name>') # Route_1
api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2

if __name__ == '__main__':
 import os
HOST = os.environ.get('SERVER_HOST', 'localhost')    
try:
    PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
    PORT = 5555
app.run(HOST, PORT)

首先,这篇文章帮助很大how-to-pass-urls-as-parameters-in-a-get-request-within-python-flask-restplus

改变我原来拥有的

 api.add_resource(LiveStats, '/liveStats/<string:url>') # Route_2  

对此

api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2  

摆脱了404错误,我有,但现在我注意到,它没有通过所有的网址

如果我尝试这个例子

localhost:60933/liveStats/http://address/Statistics?NoLogo=1%26KSLive=1

我明白了

Trying to get http://address/Statistics

所以它已经起飞了?NoLogo=1%26KSLive=1

你如何预防这种情况


Tags: nameimportaddapiappurlflaskget
1条回答
网友
1楼 · 发布于 2024-10-02 22:06:52

?后面的所有字符都被视为参数From the docs:

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.

For a full list of methods and attributes of the request object, head over to the Request documentation.

也许您可以对查询字符串进行编码,以便在后端将其作为单个参数检索,但不确定它是否有用

如果不想单独访问args,you can access the full query string:

request.query_string

综上所述,我认为这会对你有用:

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url + request.query_string

相关问题 更多 >