-1

I am trying to access request headers when a user visits a particular page. It is a cron function and according to this link. I should be able to identify if the request comes from the Service Account by checking for header X-Appengine-Cron. I've tried this and have been using request throughout my application with no problems however for this it returns the error:

local variable 'request' referenced before assignment

I have tried replicating other functions which utilise request however there is no issue there. I am using a very basic test to check it is working:

from flask import (
    Blueprint, Flask, flash, g, redirect, render_template, request, url_for
)

@app.route('/cloud-datastore-export', methods = ['GET'])
def cloud_datastore_export():
  test = request.headers.get('X-Appengine-Cron')

I expect test to contain X-Appengine-Cron value.

user3385136
  • 513
  • 1
  • 7
  • 20
  • Possible duplicate of [How to get http headers in flask?](https://stackoverflow.com/questions/29386995/how-to-get-http-headers-in-flask) – mr_m1m3 Apr 24 '19 at 13:25

1 Answers1

1

The message:

local variable 'request' referenced before assignment

is a good suggestion. Indeed, you did not define request anywhere in your code.

request property is "injected" under the hood by Flask when you decorate a method with @app.route.

Hence:

You will be able to access request properly only from within methods decorated with @app.route where app is an instance of flask.Flask class.

For example:

from flask import Flask

# (some code here)
app = Flask(__name__)

@app.route('/path/to/this/method')
def my_handler():
    headers = request.headers
    # (some more logic here)
mr_m1m3
  • 323
  • 1
  • 2
  • 12