How to make web.py work with livereload - python

I'm using web.py for an app and I'd like to use livereload while being in development but I can't figure out how to make the two get along?
app.py
import web
from livereload import Server
urls = (
'/', 'index'
)
class index:
def GET(self):
return "Hello, Kitty"
if __name__ == '__main__':
app = web.application(urls, globals()).wsgifunc()
server = Server(app)
server.serve()
I'm following https://github.com/lepture/python-livereload
server = Server(app.wsgi_app)
server.serve()
in my terminal I type
livereload app.py
and I see
[I 161130 14:05:03 server:283] Serving on http://127.0.0.1:35729
[I 161130 14:05:03 handlers:60] Start watching changes
[I 161130 14:05:03 handlers:62] Start detecting changes
but in the browser when loading http://127.0.0.1:35729 I see this
import web
from livereload import Server
urls = (
'/', 'index'
)
class index:
def GET(self):
return "Hello, Pussy"
if __name__ == '__main__':
app = web.application(urls, globals()).wsgifunc()
server = Server(app)
server.serve()
I see the python script rendered as plain tex.
Update
I decided to give the whole thing a second try, and succeeded, good for me :)
from livereload import Server
import web
from nestpas.views import *
from nestpas.urls import *
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# web.config.debug = False
web.ctx.debug = False
app = web.application(urls, globals(), autoreload=False)
webapp = app.wsgifunc()
if __name__ == '__main__':
## app.run()
server = Server(webapp)
server.watch('static/', 'templates/', 'nestpas/')
server.serve(port=8080, host='localhost')
The files I'm using are stored in static, templates and nestpas which is where the Python modules are stored. I ran into some issues having sessions stored on disk, but I managed to change that as well by using the DBStore instead
from livereload import Server
import web
from nestpas.views import *
from nestpas.urls import *
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# web.config.debug = False
web.ctx.debug = False
app = web.application(urls, globals(), autoreload=False)
webapp = app.wsgifunc()
# Setup session storage
db = web.database(dbn='sqlite', db='dev.db')
store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store)
if __name__ == '__main__':
## app.run()
server = Server(webapp)
server.watch('static/', 'templates/', 'nestpas/')
server.serve(port=8080, host='localhost')
The next goal is to figure out how to use Livereload only when on localhost and not have to think about it when deploying to production.

Related

Python flask app with Nginx and uWSGI gives Internal Server Error when writing it as class

I am building a API that uses flask. I am going to use uWSGI and NGINX in production. The API is working as it is, but I am trying to rebuild it to use classes. When I run it after I have build it as a class it gives me Internal Server Error.
The following files are working:
src/server.py
from flask import Flask
app = Flask(__name__)
#app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import app
if __name__ == "__main__":
app.run()
When I try to build it as class then I get Internal Server Error
src/server.py
from flask import Flask
class Main:
app = Flask(__name__)
def __init__(self):
#self.app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
main = Main()
main.app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import Main
if __name__ == "__main__":
main = Main()
main.app.run()

ModuleNotFoundError: No module named '__main__.web_app'; '__main__' is not a package while importing package from sub folder

I'm getting above error while running my app. I want to import app from web_app/init.py into run.py file to run on gevent. My project structure is like:
myapp
|---config.ini
|---run.py
|---web_app
|----__init__.py
run.py
from gevent.pywsgi import WSGIServer
import configparser
from .web_app import app
# from web_app.__init__ import app
config = configparser.ConfigParser()
config.read('C:/workspace/Python/myapp/config.ini')
PORT = config.get('SERVER', 'PORT')
PORT = int(PORT)
if __name__ == '__main__':
print('Serving on port ', PORT)
WSGIServer(('localhost', PORT), app).serve_forever()
__init.py
from flask import Flask
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/myapp'
logger = log_configuration.get_logger(__name__)
def simple(env, resp):
resp(b'200 OK', [(b'Content-Type', b'application/json')])
return [b'Hello Verimed User']
#app.route('/test', methods=['GET'])
def test():
return jsonify({'tasks': "task"})
If I keep run.py beside init then it's working fine. But I want to keep run.py outside web_app folder.
How to rosolve this. I tried all the way.
Have you tried it without the "." in front of "web_app"?
from web_app import app
You can find some more info in the following link: relative imports
I resolved above problem after added following code into the run.py.
import sys
sys.path.append('../web_app')
sys.path.insert(0,'./web_app')

Flask app not running on development configuration

i am running a flask application, the app is running but not following the configurations i have set.This is the config file
import os
class Config(object):
"parent configuration class"
DEBUG= True
class DevelopmentConfig(Config):
"Configurations for Development"
DEBUG = True
connectionVariables="dbname='store-manager' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='development'
class TestingConfig(Config):
"""Configurations for Testing,"""
TESTING = True
DEBUG = True
connectionVariables="dbname='store-manager-test' user='postgres' password="1235" host='localhost' port='5432'"
os.environ['ENVIRONMENT']='testing'
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig
}
Whenever i run the app it runs on testing mode even when i have specified development, however, if i remove the testing configuration, it runs on development environment.
This is how am creating the app
from flask import Flask
from flask_restful import Api
from instance.config import app_config
from connection import DbBase
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(app_config[config_name])
return app
This is how am running it.
import os
from app import create_app
config_name = 'development'
app = create_app(config_name)
# method to run app.py
if __name__ == '__main__':
app.run()
Depending on how you're actually running it and on what platform, you need to be sure to specify the location of the config.file.
export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
or for windows
set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg
I'm not seeing it in the above description, so this may the the problem.
Flask Doc on using a config File

Server not responding although the webhook to Telegram Bot API is set up

I run this script on Pythonanywhere. Webhook gets set up, but when I try using the webhook_handler it gives me "Bad Request The browser (or proxy) sent a request that this server could not understand". What am I missing?
import sys
import os
import time
sys.path.append(os.path.join(os.path.abspath('.'), 'path/to/virtualenv/'))
from flask import Flask, request
import telegram
# CONFIG
TOKEN = '<token>'
HOST = 'username.pythonanywhere.com' # Same FQDN used when generating SSL Cert
PORT = 8443
CERT = "ssl_certs/cert.pem"
CERT_KEY = "ssl_certs/key.pem"
bot = telegram.Bot(TOKEN)
app = Flask(__name__)
#app.route('/')
def hello():
return '<h1> BITCONNECT!!! </h1>'
#app.route('/' + TOKEN, methods=['POST'])
def webhook_handler():
update = telegram.Update.de_json(request.get_json(force=True), bot)
bot.sendMessage(chat_id=update.message.chat.id, text='Hello, there')
return '<h1> OK </h1>'
def setwebhook():
bot.setWebhook(url = "https://%s/%s" % (HOST, TOKEN), certificate = open(CERT, 'rb'))
if __name__ == '__main__':
context = (CERT, CERT_KEY)
setwebhook()
time.sleep(5)
app.run(host = '0.0.0.0', port = PORT, debug = True)
And here's the WSGI configuration file:
import sys
# add your project directory to the sys.path
project_home = u'/home/username/project'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from main import app as application

Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error)

I get the below error when I try and start Flask using uWSGI.
Here is how I start:
> # cd ..
> root#localhost:# uwsgi --socket 127.0.0.1:6000 --file /path/to/folder/run.py --callable app - -processes 2
Here is my directory structure:
-/path/to/folder/run.py
-|app
-|__init__.py
-|views.py
-|templates
-|static
Contents of /path/to/folder/run.py
if __name__ == '__main__':
from app import app
#app.run(debug = True)
app.run()
Contents of /path/to/folder/app/__init__.py
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
#from flaskext.babel import Babel
from config import basedir
app = Flask(__name__)
app.config.from_object('config')
#app.config.from_pyfile('babel.cfg')
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'login'
login_manager.login_message = u"Please log in to access this page."
from app import views
*** Operational MODE: preforking ***
unable to find "application" callable in file /path/to/folder/run.py
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 26972, cores: 1)
spawned uWSGI worker 2 (pid: 26973, cores: 1)
I had problems with the accepted solution because my flask app was in a variable called app. You can solve that with putting just this in your wsgi:
from module_with_your_flask_app import app as application
So the problem was simply that uwsgi expects a variable called application.
uWSGI doesn't load your app as __main__, so it never will find the app (since that only gets loaded when the app is run as name __main__). Thus, you need to import it outside of the if __name__ == "__main__": block.
Really simple change:
from app import app as application # for example, should be app
if __name__ == "__main__":
application.run()
Now you can run the app directly with python run.py or run it through uWSGI the way you have it.
NOTE: if you set --callable myapp, you'd need to change it from as application to myapp (by default uwsgi expects application
The uWSGI error unable to load app 0 (mountpoint='') (callable not found or import error) occured for me if I left out the last two lines of the following minimal working example for Flask application
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
else:
application = app
I am aware that this already implicitly said within the comments to another answer, but it still took me a while to figure that out, so I hope to save others' time.
In the case of a pure Python Dash application, I can offer the following minimal viable code snippet:
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div( html.H1(children="Hello World") )
application = app.server
if __name__ == "__main__":
app.run_server(debug=True)
Again, the application = app.server is the essential part here.

Categories

Resources