I am a new programmer and I am trying to connect my bot to flask to create a URL for discord.
when I run it, it doesn't do it. Am I missing a line here because it is not coming up with an error but it will not run either.
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
app.run(host='0.0.0.0',port=5000)
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run()```
Can someone point me in the right direction? I normally work on python 3.
Thank you
Try running the app when checking the name of your code, not in home() function:
from flask import Flask
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run(host='0.0.0.0',port=5000)
Related
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def index():
print('hello')
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
the index function is run whenever there is a request, so it is pressed on the "hello" console screen every time the site is refreshed or entered. So how can I always print "hello" in real time without refreshing this page?
What do you mean, saying "always"?
When you run flask app it starts in main thread, so if you want to make some worker(who for example prints your hello word), just create a new thread, and put in there.
Example:
from flask import Flask,render_template
import threading,time
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def start_new_thread():
def worker(arg1,arg2):
while(True):
print("hello")
time.sleep(2)
thread = threading.Thread(target=worker,args=("your argument","sencond one"))
thread.start();
if __name__ == '__main__':
start_new_thread()
app.run(debug=True)
print("OK")#never be printed because app.run starts in main thread
I want to use the Flask as my RESTful API server, but the main thread hangs and it doesn't execute the code after the app.run().
In util/restAPI.py
from flask import Flask
app = Flask('__name__')
#app.route('/')
def index():
return "Hello, World!"
In main.py
from util import restAPI
if __name__ == "__main__":
restAPI.app.run()
print "haha"
Should I use threads or something else to help me?
I wrote the following python code
import thread
from flask import Flask
app = Flask(__name__)
COOKIE =""
#app.route('/')
def index():
return COOKIE
def request_cookie():
global COOKIE
while 1:
%SOME CODE WHICH GET COOKIE FROM WEB SITE%
sleep 5
if __name__ == '__main__':
app.run(debug=True)
t1 = thread.start_new_thread(get_cookie(), ())
t1.start()
When I run this code. REST server starts but the thread doesn't start.
How can I fix it so that REST server starts and parallely runs the new thread to fetch cookie from a remote site.
You are doing app.run(debug=True) which starts the web server and waits for it to complete. Since it doesn't complete till you terminate the server, the next line is not executed.
So for your thread to start, first start the thread and then start the server.
just change :
if __name__ == '__main__':
t1 = thread.start_new_thread(get_cookie(), ())
t1.start()
app.run(debug=True)
You have to run thread before app.run() because app.run() runs endless loop which works till you stop server.
Working example:
from flask import Flask
import threading
import time
app = Flask(__name__)
COOKIE = 0
#app.route('/')
def index():
return str(COOKIE)
def request_cookie():
global COOKIE
while True:
COOKIE += 1
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=request_cookie)
t1.start()
app.run(debug=True)
Consider the following minimal working flask app:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "I am /"
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
r = requests.get("http://127.0.0.1:5000/api")
return "I am /" # This never happens :(
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
So my questions are: Why does this happen and how can I fix this?
You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.
You'll need to enable threading:
if __name__ == "__main__":
app.run(threaded=True)
or use a more advanced WSGI server; see Deployment Options.
I have a bottle app that I eventually wan't to deploy on apache (just fyi in case that's important).
Now I need to run a function once after the bottle app is started. I can't just put it into a routed function because it has to run even if no user has accessed the site yet.
Any best pratice to do this ?
The function starts a APScheduler Instance and adds a jobstore to it.
Here's what I do.
def initialize():
//init whatever you need.
if __name__ == '__main__':
initialize()
#bottle.run(port='8080', yatta yatta)
Honestly your problem is simply a sync vs async issue. Use gevent to easily convert to microthreads, and then launch each separately. You can even add a delay either in your function or before with gevent.sleep if you want to wait for the web server to finish launching.
import gevent
from gevent import monkey, signal, spawn, joinall
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from bottle import Bottle, get, post, request, response, template, redirect, hook, abort
import bottle
#get('/')
def mainindex():
return "Hello World"
def apScheduler():
print "AFTER SERVER START"
if __name__ == "__main__":
botapp = bottle.app()
server = WSGIServer(("0.0.0.0", 80), botapp)
threads = []
threads.append(spawn(server.serve_forever))
threads.append(spawn(apScheduler))
joinall(threads)
Create an APScheduler class.
Look at examples of object use and creation in this same site bacause it's too general to give an especific example to copy.
I don't know if this helps.
class Shed(object):
def __init__(self): # this to start it
# instruccions here
def Newshed(self, data):
# Call from bottle
# more methods ...
...
# init
aps = Shed() # this activates Shed.__init__()
...
# in the #router
x = aps.Newshed(data) # or whatever
Anyway I'm still learning this stuff and it's just an idea.
import threading
import bottle
def init_app():
def my_function_on_startup():
# some code here
pass
app = bottle.app()
t = threading.Thread(target=my_function_on_startup)
t.daemon = True
t.start()
return app
app = init_app()
#app.route("/")
def hello():
return "App is running"
if __name__ == "__main__":
bottle.run(app, host='localhost', port=8080, debug=True)