Can Python Requests library be used on Google App Engine?

前端 未结 7 1103
温柔的废话
温柔的废话 2020-11-29 06:01

Can I use Requests on Google App Engine? I think this library is perfect to create a REST client.

7条回答
  •  猫巷女王i
    2020-11-29 06:24

    Yes you can use the requests module. GCP does not support the use of Requests library out of the box. So we will have to make some tweeks to make it work. In order to deploy an application on the Google App Engine, we need to make a main.py(where main python flask app resides) and app.yaml(configuration file needed to run it in GCP). Here is a sample code for the app.yaml file for python 2.7 environment

    runtime: python27
    api_version: 1
    threadsafe: true
    
    handlers:
    - url: /.*
      redirect_http_response_code: 301
      script: main.app
    
    libraries:
    - name: flask
      version: 0.12
    

    Now we need to configure the requests library to use URLfetch internally. To use requests, we'll need to install both requests and requests-toolbelt using the vendoring instructions. (https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27#installing_a_library). Basically we need to install our custom libraries.

    1. Create a directory to store your third-party libraries, such as lib/ mkdir lib
    2. Upload the requests and requests-toolbelt libraries from your system or download them directly into the lib folder created in earlier step.
    3. Use pip (version 6 or later) with the -t flag to copy the libraries into the folder you created in the previous step. For example: pip install -t lib/ (pip install -t lib/ requests)
    4. Create a file named appengine_config.py in the same folder as your app.yaml file.
    5. Edit the appengine_config.py file and provide your library directory to the vendor.add() method. Sample appengine_config.py file

      from google.appengine.ext import vendor
      # Add any libraries install in the "lib" folder.
      vendor.add('lib/requests')
      vendor.add('lib/requests_toolbelt')
      
    6. Once installed, use the requests_toolbelt.adapters.appengine module to configure requests to use URLFetch. Copy the below code to the start of your main.py file

      import requests
      from requests_toolbelt.adapters import appengine
      appengine.monkeypatch(validate_certificate=True)
      

    (https://cloud.google.com/appengine/docs/standard/python/issue-requests)

    Now we can easily use the requests library to make get/post requests. Test your app:

    dev_appserver.py --port= app.yaml
    

提交回复
热议问题