How do I run a Flask application directly in the browser? [duplicate] - python

This question already has answers here:
How can I open a website in my web browser using Python?
(10 answers)
Closed 1 year ago.
I want to start my Flask application directly in the browser when I run my Python file. I now just copied the localhost address into my browser and started it that way. Is it possible to do it without copying the link every time?

Try this:
import webbrowser
from flask import Flask
app = Flask(__name__)
#your staff
#app.route("/")
def hello():
return("Hello World!")
def open_browser():
webbrowser.open_new('http://127.0.0.1:5000/')
if __name__ == "__main__":
# the command you want
open_browser()
app.run(port=5000)

Use the webbrowser module:
import webbrowser
webbrowser.get("google-chrome").open("https://www.bing.com")
You can replace 'google-chrome' with another browser you would like.

Related

How to make apscheduler not double execute? [duplicate]

This question already has answers here:
Why does running the Flask dev server run itself twice?
(7 answers)
Closed 12 months ago.
I have the apscheduler working but for some reason when it writes to my file it makes a double-entry every time the BackgroundScheduler is called.
I'm not understanding why it writes 2 lines and the timestamp will be varied by a few milliseconds in the .txt file
I only want the 1 entry, so I can eventually have it written to a database but I need to understand what is making it double executes
I don't see where in my code that it would make it double write.
Please help thank you in advanced
main.py
from flask import Flask, render_template
from flask_caching import Cache
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from datetime import date
from apscheduler.schedulers.background import BackgroundScheduler
from market_data import MarketData
import os
sched = BackgroundScheduler()
sched.start()
current_year = date.today().year
data = MarketData()
def grab_every_five():
p_data = get_c_data()
with open(file='data.txt', mode='a', encoding='utf-8') as f:
f.write(f'{p_data}\n')
sched.add_job(grab_every_five, 'interval', minutes=1)
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
app = Flask(__name__)
cache.init_app(app)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
ckeditor = CKEditor(app)
Bootstrap(app)
#app.route('/', methods=['GET', 'POST'])
def home_page():
c_data = get_c_data()
return render_template("index.html",
year=current_year,
asset_count="{:,.0f}".format(c_data['active']),
fiat_total="{:,.2f}".format(c_data['total_market_cap']),
per_asset="{:,.2f}".format(c_data['value_per_active']),
per_all_asset="{:,.2f}".format(c_data['value_per_all']),
new_asset="{:,}".format(c_data['total_asset']),
country="{:,.2f}".format(c_data['asset_per_country']),
all_asset="{:,}".format(c_data['total_asset']),
time_stamp = c_data['time_stamp']
)
#cache.cached(timeout=60, key_prefix='c_data_cache')
def get_c_data():
temp_data = data.get_data()
return temp_data
if __name__ == "__main__":
app.run(debug=True)
Ok i found the answer in this post apscheduler in Flask executes twice
It turns out with debug mode on it has the reloader also load an instance of the apscheduler
The easiest and fastest fix was to turn off the reloader as mentioned in the article I've linked to
I just had to add this line of code:
app.run(use_reloader=False)

Python Tkinter with Flask API and Subprocess

Could I run a function from another python file inside subprocess?
I use pyinstaller to convert the tkinter to an executable file. As much as possible I would like to deploy/run the .exe file to another computer without installing python.
#gui.py
from tkinter import *
import os
import subprocess
root = Tk()
root.geometry("300x150")
def backendStart():
subprocess.Popen(["test.py"], shell=True)
label = Label(root, text="Connection String", fg="grey", font=("Helvetica", 15, "bold"))
label.pack(pady=(0,3))
root.after_idle(backendStart)
root.mainloop()
Here is my sample app.py
from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import random
from connection import cursor
app = Flask(__name__)
app.config["DEBUG"] = True
api = Api(app)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("connect")
def ClientConnection():
print("Client is Connected")
#socketio.on("realtime", namespace="/sample-socket")
def RealTimeData():
while True:
num = random.randint(1, 100)
emit("data", {"random": num})
socketio.sleep(1)
#socketio.on("disconnect")
def ClientDisconnected():
print("client has disconnected")
class HomePage(Resource):
def get(self):
return jsonify(msg="hello world")
api.add_resource(HomePage, "/")
if __name__ == '__main__':
socketio.run(app, host="192.168.0.109", port=5000)
Currently I made a .spec file for configurating the names, logo, and files/libs included. The .exe file work as long as I pasted the app.py inside the build folder along with the connection.py for the database.
But with this set up I do need to install python along with the libraries I used for the app.py and connection.py
Could I run a function from another
python file inside subprocess?
you can use multiprocessing.Process()
Edit:
For an expert's answer, see here
Alternate solution:
Lets say you want to run app.exe (which is app.py), you can pack all of them into one folder (--onedir) and put those exe's and pyd's subfolders.... together, like
gui
----flask (and other folders)
----*.pyd
----app.exe
----gui.exe
----python39.dll
you will need a custom spec file to do that.
see https://pyinstaller.readthedocs.io/en/stable/spec-files.html#multipackage-bundles

Flask program not starting webbrowser in python

I am trying to make a simple program that opens the web browser when you go to a specific URL in flask.
I am using nginx with uwsgi, to work with flask, running on ubuntu desktop 18.04.
from flask import Flask
import webbrowser
app = Flask(__name__)
#app.route("/test")
def test():
#this is where a new webbrowser should be opened:
webbrowser.open_new_tab("https://google.com")
return "test!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
I expect a new tab of the webbrowser to be opened on the server machine but nothing happens
Do you have a default browser set? You need a default set.
From webbrowser:
If the environment variable BROWSER exists, it is interpreted as the os.pathsep-separated list of browsers to try ahead of the platform defaults.
Another example from the same Python reference page demonstrates you need a window open to use open_new_tab() function:
Here are some simple examples:
url = 'http://docs.python.org/'
# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
Ideally, You create a controller object specifying your browser of choice from the table in that link, such as "mozilla", "chrome", "safari" etc., then use the open_new_tab() function on that controller.
https://docs.python.org/3.5/library/webbrowser.html#browser-controller-objects
UPDATE:
So I tried this
import webbrowser
def main():
# this is where a new webbrowser should be opened:
webbrowser.open_new_tab("https://google.com")
return "test!"
if __name__ == "__main__":
main()
And I can open a new tab irrespective if a window is open.
So it works for a simple python script.
Are you saying that when you run you flask app, and try to do a GET request at http://yourip-or-domain-name/test your browser doesn't open?
(Assumption here is port 80 as you don't bind an explicit port in your app.run() call.

Close python script and reopen it

i have a python script that i want to close console and then execute again the script from the beginning. Can you help me with this?
I need to close it when i execute a function on the script. Then reopen the file so it's ready again for doing something.
You should import your script instead. You can import python files from same directory. An example:
rerun.py:
def print_stuff():
print('stuff')
runner.py:
from rerun import print_stuff
print_stuff()
Use flask. It is made for this. Go take a look at http://flask.pocoo.org/docs/1.0/quickstart/.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def some_function():
print('do stuff here')

Python program seems to be running twice [duplicate]

This question already has answers here:
How to stop Flask from initialising twice in Debug Mode? [duplicate]
(2 answers)
Closed 8 years ago.
I have a python program which is running Flask. I noticed a strange thing, it looks like the program is running twice, which I do not want.
Here is the file for starting the program(runserver.py, in the root folder /):
from myapp import app
if __name__ == "__main__":
print "woho"
app.run(host='0.0.0.0',debug=True)
When running this, I can see two "woho" in the terminal, indicating that something is strange.
in the folder /myapp I have __init__.py:
from flask import Flask
app = Flask(__name__)
import myapp.views
and then in my views.py (also in /myapp) I have all the views like:
from myapp import app
from flask import render_template
#app.route('/')
def index():
return render_template('index.html')
it's due to the reloader of flask/werkzeug, which reloads automatically when you change the code.
so give debug=False if you don't want/need that, e.g. for "production".
How to stop Flask from initialising twice in Debug Mode?

Categories

Resources