URL Handler not working in Goole app engine and flask Application - python-2.7

I'm here to ask a silly question, unfortunately I can't figure out with it.
I have a Google app Engine project developed with Flask web framework.
The structure of my project is like that (in uppercase are the directories, while in lowercase the files):
> -PROJECT DIR
> -APP
> -API
> -HANDLERS
> home.py
> -TEMPLATES
> home.html
- flask_app.py
> app.yaml
> appengine.config.pu
In home.py I am just rendering /TEMPLATES/home.html
from flask import render_template
from app.flask_app import app
#app.route('/')
def home():
return render_template('home.html')
This is the structure of app.yaml files:
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: app.flask_app.app
When i start to debugging and try to access localhost at http://127.0.0.1:8080/ instead of rendering the templates it appears to me the following error Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Is that something wrong with app.yaml file? I think it is all correct, even the url.
EDIT
flask_app.py
import appengine_config
import logging
from app import app_secret_key
from flask import Flask
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config.from_object(__name__)
CSRF_PROTECT = CSRFProtect(app)
if appengine_config.GAE_DEV:
logging.warning('Using a dummy secret key')
app.secret_key = 'my_dummy_secret_key'
app.debug = True
else:
app.secret_key = app_secret_key.secret_key

You forgot import HANDLERS.home at the end of flask_app.py
This is required on your application, Flask need to know which files register views or route.

Related

Setup flask up on cpanel Error: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later

Here is the problem. I have uploaded the files and created the app. But after modifying the passenger_wsgi.py file and refreshing the app, this error page is shown: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later.
Here is the directory structure:
Home/user/myproject/
*****************/main/
*****************/auth/
*****************/aritcles/
*****************/errors/
*****************/static/
*****************/templates/
*****************/users/
****************/__init__.py
****************/passenger_wsgi.py
*********/public_html
*********************/.htaccess
__init__.py file:
from flask import Flask, request, session, current_app
from flask_sqlalchemy import SQLAlchemy
from .config import config
from flask_login import LoginManager, current_user
db = SQLAlchemy()
login_manager = LoginManager()
# login route end_points
login_manager.login_view = 'auth.login'
def create_app(config_name=config['production']):
app = Flask(__name__)
app.config.from_object(config_name)
db.init_app(app)
login_manager.init_app(app)
from .main import main
from .auth import auth
from .users import users
from .errors import errors
from .articles import articles
app.register_blueprint(main, url_prefix='')
app.register_blueprint(auth, url_prefix='/auth')
app.register_blueprint(errors, url_prefix='/errors')
app.register_blueprint(users, url_prefix='/users')
app.register_blueprint(articles, url_prefix='/articles')
return app
passenger_wsgi.py file:
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from myproject import create_app
application = create_app()
Auto generated .htacces file:
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/user/myproject"
PassengerBaseURI "/"
PassengerPython "/home/user/virtualenv/myproject/3.9/bin/python"
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
SetEnv TWILIO_ACCOUNT_SID *************************
SetEnv TWILIO_AUTH_APP_TOKEN qydYjO9wKRdG7cMEe***************
SetEnv TWILIO_AUTH_TOKEN e8964a3d51627e4*******************
SetEnv TWILIO_PHONE_NUMBER +1**********
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END
Project creation configuration:
python version: 3.9.12
application root: project
application url: mydomaine
Then, I added for environment variables and install all required packages.
I still can't figure out what's wrong. I would be grateful for any help. Thanks in advance.
I tried these links: [https://stackoverflow.com/questions/75116826/deploying-simple-flask-app-on- shared-hosting-using-cpanel-but-only-root-url-can], [https://stackoverflow.com/questions/63106913/python-flask-app-routing-in-cpanel-can-only-access-root-url/63971427?newreg=aacb5dd4e5ad448cb94a35e97192ce4b]

Cannot import module to begin basic Flask app

So I'm following a beginners tutorial on Flask and for whatever reason am getting an error on what is essentially the very first step.
I first created an "app" directory where I created a python file for "init.py" which contains the following code:
from flask import Flask
app = Flask(__name__)
from app import routes
I then created a "routes.py" python file in the same directory:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Finally (and this is where the problem stems from), I created a python file named "microblog.py" which is located in the same folder as the "app" directory:
from app import app
I then go to my virtual environment and run (using cmd windows):
set FLASK_APP=microblog.py
So far so good, however when I try to run the following code in cmd:
flask run
I get the following error:
ImportError: cannot import name 'app' from 'app' (C:\Users\Grae_\microblog\app\__init__.py)
If any further clarification is needed, here are my file locations:
C:\Users\Grae_\microblog
C:\Users\Grae_\microblog\app
C:\Users\Grae_\microblog\__init__.py
C:\Users\Grae_\microblog\routes.py
C:\Users\Grae_\microblog\venv
C:\Users\Grae_\microblog\microblog.py
Apologies if this is really obvious, I'm just obviously very new to Flask and have been stuck on this for a while.
Thanks
The issue here is on python package "app". The directory should have a file named __init__.py instead of init.py.
For example, you rename the file init.py to __init__.py and replace content with below code it should work
from flask import Flask
app = Flask(__name__)
def start():
from app import routes
start()
You can do something like this:-
test.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Index!"
#app.route("/hello")
def hello():
return "Hello World!"
#app.route("/members")
def members():
return "Members"
#app.route("/members/<string:name>/")
def getMember(name):
return name</string:name>
if __name__ == "__main__":
app.run()
In command prompt, run the command-
python test.py
Try the URLs in your browser:
http://127.0.0.1:5000/
http://127.0.0.1:5000/hello
http://127.0.0.1:5000/members
http://127.0.0.1:5000/members/Karan/

Flask-Ask not working when using runserver pattern

Trying to add flask-Ask to an existing flask website that uses the runserver pattern where app setup done in init but app.run is called in runserver
/myapp
/myapp
__init__.py
views.py
alexa_views.py
runserver.py
This pattern works fine for Flask ( its recommended for larger apps) but Flask-Ask is failing silently when app.run(debug=True) is called from runserver.py.
If I call app.run(debug=True) in _init__.py and run that then Flask-Ask works fine and Alexa responds.
Any ideas?
code:
alexa_views.py
from flask import blueprints
from flask_ask import Ask, statement
askblueprint = blueprints.Blueprint('alexa', __name__, url_prefix='/alexa')
ask = Ask(blueprint=askblueprint)
#ask.launch
def launch():
return statement (' it works')
init.py
from flask import Flask, blueprints
from myapp.alexa_views import askblueprint
app = Flask(__name__)
app.register_blueprint(askblueprint)
# lots of other unrelated configuration here - db etc
# running app here causes Flask-Ask to work!
# if __name__ == '__main__':
# app.run(debug=True)
# late import of views to break circular import
import myapp.views
runserver.py
# running this starts website normally but Flask-Ask does nothing
from myapp import app
if __name__ == '__main__':
app.run(debug=True)
I am going to close this.
The problem does exist in my real app but this simple example now works fine so I will have to dig deeper to find something I can demonstrate.
Bill

setting up Django app to work on google app engine GAE (app.yaml & main.py)

I have a working Django app that I was able to get functioning on Heroku. The structure is project named 'untitled' and an app named 'web' such that the structure is:
project_root
static
templates
untitled
--->init.py
--->settings.py
--->urls.py
--->wsgi.py
web
--->init.py
--->admin.py
--->apps.py
--->models.py
--->tests.py
--->urls.py
--->views.py
This is a fairly basic app that I can get working outside of GAE (local and on Heroku), however, I'm getting stuck on the app.yaml and main.py requirements for GAE.
My app.yaml is:
application: seismic-interpretation-institute-py27
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
libraries:
- name: django
version: "latest"
and my main.py (generated from PyCharm) is
import os,sys
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Finally, the output that is reported when running locally is
It seems that the error,
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
is causing my problems. I am not exactly sure how to fix it.
try replace
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
to
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled.settings")
from django.conf import settings
settings._target = None

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