syntax error, import os using flask - python

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.

Related

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 do you make flask execute a function via the app.run command?

I have been trying to follow the tutorials to get flask apps to run on Heroku, like this one: https://dev.to/emcain/how-to-set-up-a-twitter-bot-with-python-and-heroku-1n39.
They all tell you to put this in your code in a file server.py:
from flask import Flask
app = Flask(__name__)
app.run(host='0.0.0.0')
And then run the app via the following command:
python3 server.py
But the tutorials don't explain how to connect the actual function you want to run using the app. In my case, I have a File testbot.py that has the function test(arg1) that contains the code I want to execute:
def test(arg1):
while(1):
#do stuff with arg1 on twitter
I want to do something like this:
from flask import Flask
from testbot import test
from threading import Thread
app = Flask(__name__)
app.addfunction(test(arg1='hardcodedparameter'))
app.run(host='0.0.0.0')
So that when the app runs my test() function executes with the argument. Right now my server is starting, but nothing is happening.
Am I thinking about this correctly?
*Edit: I got it working with the solution, so my server.py now looks like this:
from flask import Flask
from testbot import test
def main_process():
test("hardcodeparam")
app = Flask(__name__)
Thread(target=main_process).start()
app.run(debug=True,host='0.0.0.0')
And now test runs as expected.
Before app.run, register the function with a path, e.g.
#app.route('/')
def test(): # no argument
... do one iteration
return 'ok'
Then visiting the URL will trigger the function. Sites such as https://cron-job.org/ can automate that visiting on a regular basis for free, as suggested here.
If the regular intervals aren't good enough, then you could try:
#app.route('/')
def index(): # no argument
return 'ok'
def test():
while True:
# do stuff
from threading import Thread
Thread(target=test).start()
app.run(...)
You will probably still need to have a job regularly visiting the URL so that Heroku sees that the server is alive and in use.

How I can pass environment variables to my flask application

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.

flask 'hello world' not working

I copy pasted the flask's 'hello world' app from their website and am trying to run it. I get an error message in Chrome saying
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.
Here is the 'hello world' app straight from flasks website
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.debug = True
app.run()
What I have tried:
-temporarily disabling Avast!
-disabling windows firewall
-ensuring that the flask module is installed
This was working a couple days ago actually...
I don't know why but when I change
app.run()
to
app.run(port=4996)
it starts working. No idea why the default port is throwing an error. Oh well.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__name__':
app.run()
app.run(port=5000)
For Windows machines you can use the command in cmd:
set FLASK_APP=python_file.py
flask run
Some other process is running on port 5000. It may be you still have an old Flask process running, with broken code. Or a different web server altogether is running on that port. Shut down that process, or run on a different port.
You can switch to using a different port with the port argument to app.run():
app.run(port=8080)
If you can't figure out what process is still bound to port 5000, use the Windows Resource Monitor or run netstat -a -b from a command line. See How can you find out which process is listening on a port on Windows?
I think you are trying to copy the route generated through your flask program in cmd by pressing ctrl+c which quits your running flask program . i was also doing the same.just try to type the route generated by your flask program on your browser . it will definitely resolve your problem.
Where your python file store is, use cmd and then go on your file store directory, then
set FLASK_APP=filename.py
After this your flask run cmd will work.
from flask import Flask
app = Flask(__name__) # creating app
#app.route('/', methods['GET']) #routing it to the home page
def home(): #function
return "hello world"
app.run(port=5000, debug=true) #function call by the app
Add port and use methods whatever your need is USE GET in your case and try to remove your cache and run the this code it will definitely work.

How to obtain values of parameters of get request in flask?

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

Categories