How I can pass environment variables to my flask application - python

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.

Related

Config var does not work in python Heroku app

I have an application that uses some environments variables like host, users, dbname to protect sensive data in a database connection. In local ambient, using localhost with Pycharm IDE that works fine!!! But when I upload code to Heroku, it don´t recognize my environment variables and app crashes.
Here is small code showing how I call variables at Pycharm IDE. That is fine for localhost:
from flask.app import Flask
from flask.templating import render_template
from flask_socketio import SocketIO, emit, send
import os
app = Flask(__name__)
host = os.environ['HOST']
dbname = os.environ['dbname']
#app.route("/")
def home():
return('<div>Host: ' + host + '</div><div>Dbname: ' + dbname + '</div>'
)
if __name__ == "__main__":
#io.run(app, debug=False)
app.run()
Here is response in local browser, that´s ok!
enter image description here
In Heroko, config var are equal variables above, follow print os settings:
Here is the result of same code uploaded to Heroku
enter image description here
And here is the return of logs --tail from heroku
enter image description here
enter image description here
Well, any suggestions to solve this problem? How can I adapt code to run in Heroku app?
Thx

App Engine Standard Python 3 environment variables undefined

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)

How to use variables created in gunicorn's server hooks?

I am using gunicorn to run my Flask application. I would like to register server hooks to perform some action at the start of the application and before shutting down, but I am confused on how to pass variables to these functions and how to extract variables created within them.
In gunicorn.conf.py:
bind = "0.0.0.0:8000"
workers = 2
loglevel = "info"
preload = True
def on_starting(server):
# register some variables here
print "Starting Flask application"
def on_exit(server):
# perform some clean up tasks here using variables from the application
print "Shutting down Flask application"
In app.py, the sample Flask application:
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/hello', methods=['POST'])
def hello_world():
return jsonify(message='Hello World')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=False)
Running gunicorn like so: $ gunicorn -c gunicorn.conf.py app:app
A bit late, but you have access to the flask application instance through server.app.wsgi(). It returns the same instance used by the workers (the one that is also returned by flask.current_app).
def on_exit(server):
flask_app = server.app.wsgi()
# do whatever with the flask app
Put the data you need to pass to the hooks into environment variables.
You can also store the data to be passed to the hooks and from them in files.
What are you trying to achieve is not possible due to the wsgi interface and the way the state is managed between requests.

syntax error, import os using flask

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.

Combining resources in Python with Flask

I' trying to combine two independent Flask apps like the example below:
from geventwebsocket import WebSocketServer, Resource
...
server = WebSocketServer(('', 8080), Resource({
'/': frontend,
'/one': flask_app_one,
'/two': flask_app_two}))
server.serve_forever()
Inside each Flask app I declare the full path, isn't that suppose to be relative path, inside flask_app_one:
from flask import Flask
app = Flask(__name__)
#app.route('/one/ping')
def ping():
return 'hello\n'
Why I should specify in #app.route('/one/ping') instead of just #app.route('/ping') since all traffic to /one will be forwarded to the corresponding app?
Let me know if you need any additional info I kept my example clean
Thank you
Finally I have managed to do it with the so called Application Dispatching and the resources found in this page:
http://flask.pocoo.org/docs/0.10/patterns/appdispatch/#app-dispatch
Thanks

Categories