Start function on run with Flask - python

I have a flask app
#app.route("/hello")
def generater():
return "hello world"
if __name__ == '__main__':
app.run()
My application runs fine, but i would like to know how I could make a request to http://127.0.0.1:5000/hello when I compile my code

You can use webbrowser to automatically open http://localhost:5000 in a web browser when running your flask app:
import webbrowser
...
if __name__ == '__main__':
webbrowser.open('http://localhost:5000')
app.run()

There are a lot of ways you could do this. You could just open up your browser to that location. You could try #jimtodd's answer and then cURL the endpoint from another terminal window.
To do it in the code, which I guess is what you want, Flask offers you some helper methods. For example there is: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.before_first_request
You can use it like this:
def foo():
pass
app.before_first_request(foo)
In the case where you want to run a script strictly on run, not just before the first request, this solution is good: Run code after flask application has started -- I guess you would use this for cold-start problems as well.

You can do this from command prompt:
set FLASK_APP=hello.py
python -m flask run
The you will see....
Running on http://127.0.0.1:5000
Now you can check the output in your browser.

Related

Flask + Wsgi returning python shell script output

I have deployed two containers flask + wsgi and nginx I have a simple code which works returning hello world.
When I try to return the output of a python shell script to a webpage I get internal server error, the script it works via cli it even prints the output of docker ps.
Working code returns a simple hello world :
# app.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello world!'
if __name__ == '__main__':
app.run(host='0.0.0.0')
Not working code i get internal server error please help im not really sure why ... or how to debug it
#!/usr/bin/env python
import subprocess
def dockers():
call = subprocess.call('docker ps', shell=True)
return call
#!/user/bin/env python
from flask import Flask
from cont import dockers
app = Flask(__name__)
print(dockers())
#app.route('/')
def hello_world():
return dockers()
if __name__ == '__main__':
app.run(host='0.0.0.0')
Dont ever try to pass an object to a web page youll have a bad time. i wrote the result into a file split the lines to a list and returned it to the webpage.

Open browser automatically when Python code is executed

I am implementing a GUI in Python/Flask.
The way flask is designed, the local host along with the port number has to be "manually" opened.
Is there a way to automate it so that upon running the code, browser(local host) is automatically opened?
I tried using webbrowser package but it opens the webpage after the session is killed.
I also looked at the following posts but they are going over my head.
Shell script opening flask powered webpage opens two windows
python webbrowser.open(url)
Problem occurs when html pages are rendered based on user inputs.
Thanks in advance.
import webbrowser
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
webbrowser.open_new('http://127.0.0.1:2000/')
app.run(port=2000)
Use timer to start new thread to open web browser.
import webbrowser
from threading import Timer
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
def open_browser():
webbrowser.open_new("http://127.0.0.1:5000")
if __name__ == "__main__":
Timer(1, open_browser).start()
app.run(port=2000)
I'd suggest the following improvement to allow for loading of the browser when in debug mode:
Inspired by this answer, will only load the browser on the first run...
def main():
# The reloader has not yet run - open the browser
if not os.environ.get("WERKZEUG_RUN_MAIN"):
webbrowser.open_new('http://127.0.0.1:2000/')
# Otherwise, continue as normal
app.run(host="127.0.0.1", port=2000)
if __name__ == '__main__':
main()
https://stackoverflow.com/a/9476701/10521959

Creating an API to execute a python script

I have a python script app.py in my local server (path=Users/soubhik.b/Desktop) that generates a report and mails it to certain receivers. Instead of scheduling this script on my localhost, i want to create an API which can be accessed by the receivers such that they would get the mail if they hit the API with say a certain id.
With the below code i can create an API to display a certain text. But, what do i modify to run the script through this?
Also if i want to place the script in a server instead of localhost, how do i configure the same?
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return ("hello world")
if __name__ == '__main__':
app.run(debug=True)
Python Version is 2.7
A good way to do this would be to put the script into a function, then import that function in your Flask API file and run it using that. For hosting on a web server you can use Python Anywhere if you are a beginner else heroku is also a good option.
If you are tying to achieve something using Python-Flask API than you can have a close look at this documentations and proceed further https://www.flaskapi.org/, http://flask.pocoo.org/docs/1.0/api/
Apart from these here are few basic examples and references you can refer for a quickstart :
1-https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
2- https://flask-restful.readthedocs.io/en/latest/
3- https://realpython.com/flask-connexion-rest-api/
You could do something like this
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class ExecuteScript:
def printScript:
return "Hello World"
api.add_resource(ExecuteScript, '/printScript')
if __name__ == '__main__':
app.run(debug=True)

Cloud9 "Unable to load http preview" Flask project

I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.

Pycharm Unexpected Result Output

I'm a beginner at Pycharm. I'm using Flask web framework to develop a basic web application. I have written a simple code to display "Hello" on my browser, which it did. Strangely, when I add something to 'Hello', such as 'Hello my name is Yusef' and re-run the program; it won't show any changes, it still appears with message 'Hello' on my browser. Any idea, what I'm missing?
Below is my code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "hello world"
if __name__ == "__main__":
app.run()
You need to clear the browser cache, this isn't a Pycharm issue, just clear your browser cache and you should be fine.
Open in incognito mode to avoid such issues.

Categories

Resources