简体   繁体   中英

Pass parameter to Flask API method

I'm pretty new to Flask APIs, so I hope this will be pretty easy to solve.

I'm working on an API (right now it has only one endpoint, but as soon as I manage to implement its functionality more will follow). I generated my API with the swagger editor and am trying to implement the methods. I managed to implement a GET method which takes no variables and returns a json file.

What I'm trying right now is to pass variable to this method to do some things.

My directory structure is like this:

swagger_server/
    |---->__main__.py
    |---->controllers
           '---->default_controller.py

My __main__.py file (I deleted a few empty lines to make this question shorter):

  1 #!/usr/bin/env python3
  3 import connexion
  5 from swagger_server import encoder
  7 
  8 def main():
  9     app = connexion.App(__name__, specification_dir='./swagger/')
 10     app.app.json_encoder = encoder.JSONEncoder
 11     app.add_api('swagger.yaml', arguments={'title': 'Test API'}, pythonic_params=True)
 12     app.run(port=8080)
 14 
 15 if __name__ == '__main__':
 16     main()

My default_controller.py :

  1 import connexion
  2 import six
  3 import os
  4 import json
 60
 61 def get_supported_types(test):  # noqa: E501
 62     """Retrieve supported types for number test
 63     param:    test = id of supported type
 64     :rtype: InlineResponse200
 65     """
 66     print(test)
 70
 71     return 'blabla'

Without a parameter I was able to receive data with curl like this curl -H 'Authorization: 0123' -H --trace-ascii /tmp/dump.txt 'http://127.0.0.1:3080/v1/supported_types'

I tried to add an extra header with -H "test: 15" , to add it to the URL http://127.0.0.1:3080/v1/supported_types?test=15 (which led to a 500 Server Error) and http://127.0.0.1:3080/v1/supported_types/?test=15 (which led to a 404 Not Found Error).

Also I read a little bit about @app.route which I tried but that didn't really work:

@app.route("/v1/supported_types/", methods=['GET'])
NameError: name 'app' is not defined

Can anyone help me pass this argument to the method?

Put name of variables on route and on method which you will use then you can handle

@my_bp.route('/my_route/<int:id_report>')
def report(id_report=1):
    report = make_pdf(Report.query.get(id_report))
    return send_file(report, attachment_filename="My_Report.pdf", as_attachment=True )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM