I am trying to access the GOOGLE_CLOUD_PROJECT environment variable in my App Engine Standard Python 3 app. According to the documentation this variable should be set at runtime. I created a simple function using Flask to demonstrate the issue:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def root():
try:
return GOOGLE_CLOUD_PROJECT
except NameError:
return 'GOOGLE_CLOUD_PROJECT undefined'
Whatever I try I keep triggering the exception and 'GOOGLE_CLOUD_PROJECT undefined' is returned. Why am I not able to access this environment variable?
By just looking at the code you provide, the reason is that this is not the way to get the value of an Environment Variable using Python. Actually, the error message you would see if you didn't have the except is that the variable GOOGLE_CLOUD_PROJECT does not exist in your Python code.
You may want to use something like this:
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def root():
try:
return os.environ['GOOGLE_CLOUD_PROJECT']
except NameError:
return 'GOOGLE_CLOUD_PROJECT undefined'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
Related
Working with Python Dash and have it working from local host, but when attempt to deploy to my python app server, I have issues.
When I keep the app as just Flask it works with this code:
from flask import Flask
import dash
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
When I try to pass the server to the Dash instance (when according to Dash docs is acceptable, I receive the error). Here is the code
from flask import Flask
import dash
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
#app.route("/")
def hello():
return "Hello World!"
I receiving the error:
AttributeError: 'Dash' object has no attribute 'route'
The docs don't say what you think they do. app is the Dash instance, not the Flask one - that is available via the server variable, so you can call route on that.
#server.route("/")
def hello():
return "Hello World!"
As Daniel Roseman said, you must use server.route instead of app.route.
However, Dash registers itself to serve the path /, overwriting your route.
Other paths not used by Dash work as expected, e.g.:
#server.route('/hello-world')
def hello():
return "Hello World!"
I am new to Python and writing a simple flask api which will connect to azure cosmos DB and return some response.
I want to pass db connection string as environment variable as going forward I need to dockerize this application.
So I am not sure how I can pass this connection string to my Flask application as environment variable and how to run and test my Flask application from command windows.
Below is my piece of code.
import os
from flask import Flask, request, render_template
from azure.storage.table import TableService, Entity
APP = Flask(__name__)
APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
connectionstring = os.environ['connectionstring']
#APP.route('/getdata')
def view_registered_guests():
print("Inside method");
table_service = TableService(connection_string=connectionstring)
table_name = 'tablebasics'
entity = table_service.get_entity(table_name, 'Harp', '2')
print(entity['email'])
print(entity['phone'])
return "Email: "+entity['email'] +" phone no: "+ entity['phone'];
if __name__ == '__main__':
APP.run(debug=True)
Any help will be appreciated.
Thanks,
Use os module
os.environ["connectionstring"]
You can set environment variables in windows cmd using SET
set connectionstring=SOMETHING
To test this i just added "connectionstring" variable and its value in system environment variables (System variables) and ran my py file and it worked.
Thanks everyone for you hints.
I'm working through RealPython and I'm having trouble with the flask dynamic route.
Everything seemed to work until the dynamic route. Now if I try to enter a "search query" (i.e. localhost:5000/test/hi) the page is not found. localhost:5000 still works fine.
# ---- Flask Hello World ---- #
# import the Flask class from the flask module
from flask import Flask
# create the application object
app = Flask(__name__)
# use decorators to link the function to a url
#app.route("/")
#app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
return "Hello, World!"
# start the development server using the run() method
if __name__ == "__main__":
app.run()
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
I can't see that other people using RealPython have had an issue with the same code, so I'm not sure what I'm doing wrong.
The reason why this is not working is because flask never learns that you have another route other / and /hello because your program gets stuck on app.run().
If you wanted to add this, all you need to do would be to add the new route before calling app.run() like so:
# ---- Flask Hello World ---- #
# import the Flask class from the flask module
from flask import Flask
# create the application object
app = Flask(__name__)
# use decorators to link the function to a url
#app.route("/")
#app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
return "Hello, World!"
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
# start the development server using the run() method
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port=5000)
Now this will work.
Note: You don't need to change the run configurations inside of app.run. You can just use app.run() without any arguments and your app will run fine on your local machine.
Try using the entire URL instead of just the IP address.
I'm using flask and I keep getting a Internal Server Error when trying to use import os commands, can anyone tell me what I'm doing wrong? This is the code that I'm using:
import os
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return os.environ['REMOTE_ADDR']
if __name__ == "__main__":
app.run(host= '0.0.0.0')
In your hello() function check if REMOTE_ADDR is set using os.environ.get('REMOTE_ADDR'), so your hello() should be as below:
def hello():
if os.environ.get('REMOTE_ADDR'):
return os.environ['REMOTE_ADDR']
else:
return 'Remote address not set'
Since, the REMOTE_ADDR isn't set, it would not find the key REMOTE_ADDR in the environment variables and will return a KeyError.
Your script is supposed to be run as a CGI script by a web-server, which sets environment variables like REMOTE_ADDR, REQUEST_METHOD, etc.
You are running the script by yourself, and these environment variables are not available. That's why you get the KeyError.
Hence, the Internal server error.
The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:
from flask import Flask
app = Flask(__name__)
#app.route("/hello")
def hello():
print request.args['x']
return "Hello World!"
if __name__ == "__main__":
app.run()
I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
What am I doing wrong?
The simple answer is you have not imported the request global object from the flask package.
from flask import Flask, request
This is easy to determine yourself by running the development server in debug mode by doing
app.run(debug=True)
This will give you a stacktrace including:
print request.args['x']
NameError: global name 'request' is not defined
http://localhost:5000/api/iterators/opel/next?n=5
For something like the case before
from flask import Flask, request
n = request.args.get("n")
Can do the trick