How to run a Flask app on CherryPy WSGI server (Cheroot) using HTTPS? - python-2.7

I am running a Python 2.7 Flask app on CherryPy Cheroot WSGI server usinh HTTP now as below.
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from MyFlaskApp import app
d = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 80), d)
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()
What would I have to to move to HTTPS from here?
I found below instruction, but it does not seem to applicable to my application.
from cheroot.server import HTTPServer
from cheroot.ssl.builtin import BuiltinSSLAdapter
HTTPServer.ssl_adapter = BuiltinSSLAdapter(
certificate='cert/domain.crt',
private_key='cert/domain.key')
Can I apply above sample to my Flask app on Cheroot? If not, what would be a simple example for Flask app on Cheroot for HTTPS?

I figured out the necessary modification.
Not much information on Flask app on Cheroot with https, so I thought I'd share it.
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from cheroot.ssl.builtin import BuiltinSSLAdapter
from MyFlaskApp import app
my_app = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 443), my_app)
ssl_cert = "[path]/myapp.crt"
ssl_key = "[path]/myapp.key"
server.ssl_adapter = BuiltinSSLAdapter(ssl_cert, ssl_key, None)
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()

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)

Telebot not responding to requests with FLask server

I am trying to deploy my telegram bot to Heroku using Flask. ALthough I followed the tutorials and set up everything the same I am not getting any result and my bot is not responding.
import requests
import pandas as pd
import telebot
from telebot import types
import random
import os
from flask import Flask, request
from requests.models import MissingSchema
URL_HEROKU = f"some_url"
TOKEN = os.environ['TOKEN']
bot = telebot.TeleBot(TOKEN, parse_mode=None)
app = Flask(__name__)
#bot.message_handler(commands=['start'])
def start(message):
#Init keyboard markup
msg = ''' Hello, how are you?'''
bot.reply_to(message, msg)
#bot.message_handler(commands=['random'])
#bot.message_handler(regexp=r'random')
def send_some(message):
bot.send_message(message.chat.id, text='Hello')
#app.route('/' + TOKEN, methods=['GET'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200
#app.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url= URL_HEROKU + TOKEN)
return "!", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
My Procfile is:
web: python telebreed.py
and my requirements.txt:
Flask==2.0.2
gunicorn==20.1.0
pandas==1.2.2
pyTelegramBotAPI==4.6.0
requests==2.26.0
do you see any mistake ? When I open my app in Heroku I only see "!" which is the character defined in getMessage() method.

cannot import name 'serve' from 'waitress'

My Sample Flask Code (wsgitest.py):
from flask import Flask
from waitress import serve
app = Flask(__name__)
#app.route('/wait')
def index():
return ("<h3>Hello World</h3>")
if __name__ == '__main__':
serve(app, host='0.0.0.0', port=5000)
waitress
Version: 1.4.3
Error
ImportError: cannot import name 'serve' from 'waitress' (C:\.....\wsgitest.py)
if your your project has one file named waitress. Import resolves to your project file rather than waitress package
your code is ok. I copy your code to my idea, it's run successfully

How to start Flask and Flask-SocketIO via the command line flask run

I started with an application that has several webservices defined. I was able to start the application via flask run on the command line. Afterwards, I integrated flask-sckoetio (i.e. I added the lines from flask_socketio import SocketIO, emit and socketio = SocketIO(app)) and now I'm not able anymore to start the server via flask run.
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
I get the following message on the console:
* Serving Flask-SocketIO app "webservices.py"
* Forcing debug mode off
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved perform
ance.
c:\program files\python36\lib\site-packages\flask_socketio\__init__.py:496: Warning: Silently ignoring
app.run() because the application is run from the flask command line executable. Consider putting app.
run() behind an if __name__ == "__main__" guard to silence this warning.
use_reloader=use_reloader, **kwargs)
So I updated my code to this:
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
if __name__ == '__main__':
socketio.run(app)
But I still get the same error message and the server doesn't start. However, if I just execute the script everything works. But why is flask run not possible anymore?
It happens because of variable __name__ is equal to "__main__" only when the file called directly with a command like python file.py. But your file was imported and his __name__ variable is setted to name of a module which import them.
Solution:
Just delete string if __name__ == "__main__":
Did you install eventlet or gevent, which are mentioned in the error message?
They are also listed under requirements in flask-socketIO documentation.
Try installing them first.
After installing one of them, you can just use flask run to start your application.

Making use of CherryPy as webserver for flask application

I have a simple flask application that works really well. I've been developing it separately from the main desktop application, I want to "plugin" the flask application into the main application. I also want to use cherrypy as the webserver as the default webserver that comes with flask is not production ready. I am not sure how to get both these to work together. My flask application code looks like this
from flask import Flask, render_template,send_from_directory
from scripts_data import test_data
from schedule_data import scheduledata
import os
app=Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/scripts')
def scripts():
test_data=t_data()
return render_template('scripts.html',data_scripts=test_data)
#app.route('/sch')
def schedules():
data_schedule=s_data()
return render_template('schedules.html',table_data=data_schedule)
if __name__=='__main__':
app.run(debug=True)
so obviously as I want to integrate into the main application I can't use app.run. Its not clear how to swap out the flask webserver for the Cherrypy Webserver
I have seen the following
from flask import Flask
import cherrypy
app = Flask(__name__)
app.debug = True
Class setup_webserver(object):
#app.route("/")
def hello():
return "Hello World!"
def run_server():
# Mount the WSGI callable object (app) on the root directory
cherrypy.tree.graft(app, '/')
# Set the configuration of the web server
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
'server.socket_port': 5000,
'server.socket_host': '0.0.0.0'
})
# Start the CherryPy WSGI web server
cherrypy.engine.start()
cherrypy.engine.block()
Class start_it_all(object)
import setup_webserver
setup_webserver.run_server()
But when I start the webserver and go to the site (0.0.0.0:5000) I get a 404?
I don't get the 404 when its just flask on its own. All I want to do is swap out the flask built-in webserver for the cherrpy webserver. I don't want to use cherrypy for anything else, as Flask will be the framework
Any suggestions? I'm on Windows and using python 2.7