how to add job by flask apscheduler api using postman - flask

from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job5',
'func': 'f_s_api.view:job1',
'trigger': 'interval',
'seconds': 50
}
]
SCHEDULER_API_ENABLED = True
def job1():
print('job add')
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
app.run(debug= True , port= 8080)
output
Serving Flask app "view" (lazy loading)
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: on
Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
Restarting with stat
Debugger is active!
Debugger PIN: 135-565-985
job add
ob add

run the flask and open the postman and http://localhost:5000/scheduler/jobs this flask apscheduler api url for add job in the form of post request then in body-->row select text type as JSON and the send the request.

Related

How to serve Flask app on waitress and socket.io using eventlet server simultaneously?

I'm using waitress server to deploy the flask app for production. I'm also using flask's socketio along with the eventlet server which requires its own app run.
Currently only serving app on waitress:
serve(app, host='0.0.0.0', port=8080)
How do I include the socket.run command for running the socket server?
socketio.run(app)
My code:
This snippet sets up server for the flask socketio on which it is to be run and in the if name part I serve the app on waitress if in prod mode.
app.py
import eventlet
async_mode = None
if async_mode is None:
try:
async_mode = 'eventlet'
except ImportError:
pass
if async_mode is None:
async_mode = 'threading'
print('async_mode is ' + async_mode)
if async_mode == 'eventlet':
eventlet.monkey_patch()
socketio = socketIO(app,cors_allowed_origins='*',async_mode=async_mode)
if __name__=='__main__':
if env_mode=='dev':
app.run(host='0.0.0.0', port=8080)
elif env_mode=='prod':
serve(app, host='0.0.0.0', port=8080)

Flask telegram bot unresponsive on server deployment

I have been running locally, without host param nor port param and it has been working well without a webhook (very unintuitive, how is just bot token enough?).
I decided to put my bot on a server. I've created a python3 file and I've now:
created the webhook on ipv4 port 8443
{"ok":true,"result":true,"description":"Webhook is already set"}
edited the lines in main:
context=('/path_to/cert.pem', '/path_to/privkey.pem')
app.run(host="xxx.xx.xxx.xxx",port="8443", ssl_context=context, debug=False)
This gives output of
* Serving Flask app 'xx'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on https://xxx.xx.xxx.xxx:8443
Press CTRL+C to quit
Bot is unresponsive.
I've used the following command and it didn't help:
sudo ufw allow 8443
I've tried running with:
context=('/path_to/cert.pem', '/path_to/privkey.pem')
app.run(host="0.0.0.0",port="8443", ssl_context=context, debug=False)
And the output is:
* Serving Flask app 'xx'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on https://xxx.0.0.x:8443
* Running on https://xxx.xx.xxx.xxx:8443
Press CTRL+C to quit
Bot is unresponsive...
Edit: bot code:
from flask import Flask
from flask import request
from flask import Response
import requests
TOKEN = "..."
app = Flask(__name__)
def parse_message(message):
print("message-->",message)
chat_id = message['message']['chat']['id']
txt = message['message']['text']
print("chat_id-->", chat_id)
print("txt-->", txt)
return chat_id,txt
def tel_send_message(chat_id, text):
url = f'https://api.telegram.org/bot{TOKEN}/sendMessage'
payload = {
'chat_id': chat_id,
'text': text
}
r = requests.post(url,json=payload)
return r
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
msg = request.get_json()
chat_id,txt = parse_message(msg)
if txt == "hi":
tel_send_message(chat_id,"Hello!!")
else:
tel_send_message(chat_id,'from webhook')
return Response('ok', status=200)
else:
return "<h1>Welcome!</h1>"
if __name__ == '__main__':
context=('path/cert.pem', 'path/privkey.pem')
app.run(host="xxx.xx.xxx.xxx",port="8443", ssl_context=context,debug=False)

Restart python Script on Server after crashing

I am currently trying to set um a server to run a tensorflow Application. It is working fine but if there are too many requests the server terminates the flask Application which is requesting the answer from my tensorflow model.
This means that the Server is useless as long as I don't restart the flask app manually with python3 flaskApp.py in the server terminal.
Is there a way to restart the Python Script automatically once it fails? <== !! main question !!
It doesn't bother me when I don't get a return value once in a while but I don't want to manually restart the flaskApp once a day.
Here is the code for my flask Application, the method 'handler' returns a probability from my tensorflow model running in the background.
from flask import Flask, redirect, request, jsonify
from modelv4 import *
from waitress import serve
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route('/', methods=['POST'])
def processjson():
data = request.get_json()
satz = data['text']
print(satz)
ruckgabe = handler(satz)
ruckgabe = round(ruckgabe*10000)
ruckgabe = ruckgabe / 100
ruckgabe = str(ruckgabe)
ruckgabe = jsonify({"ruckgabe": ruckgabe})
#ruckgabe.headers.add('Access-Control-Allow-Origin', '*')
return ruckgabe
if __name__=='__main__':
serve(app, host="0.0.0.0", port=8080)
The server is running on aws EC2 as an Ubuntu instance, so you get a basic linux terminal.
If you need any more information to answer my question, please let me know.
Since the application is running on an ubuntu server I recommend using systemd.
You can let systemd auto-restart it in case it fails or is accidentally killed.
To do this, you can add the restart option to the .service file you created specifically for your application.
How can I run my flask application as a service with systemd?
A possible configuration of your .service file could be the following:
[Unit]
Description=My flask app
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service
StartLimitIntervalSec=500
StartLimitBurst=5
[Service]
Restart=on-failure
RestartSec=5s
ExecStart= <script to start your application>
[Install]
WantedBy=multi-user.target

run discord bot inside flask

I would like to have a strife bot that accesses the Flask Database (Flask SQLAlchemy). I would like to know if there is a way to make the Discord bot run and managed via the Flask Web Application, how to connect the two so that they can interact with each other
Thanks, Regard
here is my flask configuration
# bot Client Config
client = commands.Bot(command_prefix='!', case_insensitive=True)
# Load Token Config
load_dotenv('.env')
# Token Config
TOKEN = os.getenv('TOKEN')
# Picture Extension
pict_ext = ('.jpg','.png','.jpeg')
#
# Flask Configuration
def create_app(script_info=None):
# environtment configurations
# module import
from projects.dashboard.views import dashboard_blueprint
# initialize app
app = Flask(__name__, static_url_path='')
# register blueprint
app.register_blueprint(dashboard_blueprint)
return app
running discord bot in the separate thread using thread module like this
# thread function
def flask_thread(func):
thread = Thread(target=func)
print('Start Separate Thread From Bot')
thread.start()
then add it to the main file
# main file
# function run flask with separate Thread
def run():
app.run(host='0.0.0.0', port=10000, use_reloader=False)
if __name__ == '__main__':
flask_thread(func=run)
client.run(os.getenv('TOKEN'))
running with command
python main.py
and see http://localhost:10000 in your browser

Flask / Werkzeug run_simple not displaying Exception traces

I created two flask apps: frontend and restapi (with flask-restful). I created the following runserver.py to run them in development:
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
from restapi import app as restapi_app
from frontend import app as frontend_app
application = DispatcherMiddleware(frontend_app, {
'/api': restapi_app,
})
if __name__ == "__main__":
run_simple(
'localhost',
5000,
application,
use_reloader=True,
use_debugger=True,
use_evalex=True)
Despite having use_debugger=True, whenever one of the flask-restful resources raises an error, I don't get a trace, just a 500 error
{"status": 500, "message": "Internal Server Error"}
Any ideas how to get the full trace to display? Let me know if you need more details/code.
use_debugger option of Werkzeug WSGI server only enables embedded debugger, the server is unaware of Flask app configuration values (DEBUG in this case). To propagate exceptions to the server, you need to enable debug mode for both Flask app objects yourself. Here's one way to do it:
if __name__ == '__main__':
restapi_app.debug = True
frontend_app.debug = True
run_simple(...)