I currently have my files structured as:
/xampp/code/menumaster_project
menumaster
__init__.py
menumaster_app.py
sqltables.py
In my Apache httpd.conf file I have:
<IfModule wsgi_module>
<VirtualHost *:8081>
WSGIScriptAlias /myapp C:/xampp/htdocs/flaskapp/flask.wsgi
<Directory C:/xampp/htdocs/flaskapp>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</IfModule>
flask.wsgi
import sys
sys.path.insert(0, 'C:/xampp/code/menumaster_project')
from menumaster import app as application
The file that contains all my routes is menumaster_app.py:
#app.route('/restaurants', methods = ['GET'])
I am trying to access my app on localhost through http://localhost:8081/myapp/restaurants however I am receiving a 404 error.
I'm also not sure how my app is supposed to know that menumaster_app.py is the main file that needs to be called initially.
Thanks for your help.
You need to import menumaster_app after defining your Flask app, so that the code is loaded and the routes are registered.
__init__.py
# ...
app = Flask(__name__)
# ...
from menumaster import menumaster_app
Be sure to import menumaster_app after any objects that it will import from __init__.py, to avoid circular imports.
As a side note, it is pretty confusing to name your views "menumaster_app", when that module neither defines the package menumaster nor the Flask app. Typically the file with views in it is called views.py.
This article was very helpful: http://flask.pocoo.org/docs/0.10/patterns/packages/
I ended up following what was stated there and ended up with:
menumaster
runserver.py
menumaster
views.py
sqltables.py
runserver.py
from menumaster import app
app.run(debug=True)
views.py
#app.route('/restaurants', methods = ['GET'])
__init__.py
from flask import Flask
app = Flask(__name__)
import menumaster.views
.wsgi
import sys
sys.path.insert(0, 'C:/xampp/code/menumaster')
from menumaster import app as application
Hope this helps someone.
Related
I'm trying to deploy a flask app on a shared server (hostgator) using CGI but I'm getting a URL not found error when I use the base URL (mysite.com/) and all others. I've set up a virtual environment in the public_html/ folder with python 2.7.8 and Flask 0.12.4 (newer versions of flask not supported on python 2.7.8 because they use SSLContext).
I've determined that the .htaccess file and cgi-bin/main.cgi file are configured correctly by writing a small flask hello_world app in the public_html/ folder that works and runs the website. And I've tried checking the error logs on cpanel which are empty and couldn't find any other useful logs in the file system. I've also set all the permissions to 755 which is what hostgator recommended to no avail.
My file system is this:
public_html/
flask_hello_world.py
some .html files for testing
cgi-bin/
main.cgi
server/
app.py
__init__.py
views.py
models.py (sqlalchemy models)
static/
some .html files
My .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /home4/MYSITE/public_html/cgi-bin/main.cgi/$1 [L]
Addhandler cgi-script .py .cgi
main.cgi:
#!/home4/MYSITE/public_html/venv/bin/python
import sys
sys.path.insert(0, '/home4/MYSITE/public_html/venv/lib/python2.7/site-packages/')
sys.path.insert(1, '/home4/MYSITE/public_html/server/')
from wsgiref.handlers import CGIHandler
from app import app
class ProxyFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['SERVER_NAME'] = ""
environ['SERVER_PORT'] = "80"
environ['REQUEST_METHOD'] = "GET"
environ['SCRIPT_NAME'] = ""
environ['QUERY_STRING'] = ""
environ['SERVER_PROTOCOL'] = "HTTP/1.1"
return self.app(environ, start_response)
if __name__ == '__main__':
app.wsgi_app = ProxyFix(app.wsgi_app)
CGIHandler().run(app)
And when I changed main.cgi to run flask_hello_world.py it ran just fine. Here's that code:
import flask
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return flask.send_from_directory('/home4/MYSITE/public_html/','index.html')
#app.route('/hello')
def hello():
return flask.send_from_directory('/home4/MYSITE/public_html/','hello.html')
Moving my main project .py files into the public_html folder did not solve the problem. Heres app.py and init.py from the actual project:
app.py:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Flask
##other imports including sqlalchemy
app = Flask(__name__)
app.config["CACHE_TYPE"] = "null"
# sqlalchemy setup
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database.db')
##some other configurations
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# flask login setup
login_manager = LoginManager()
login_manager.login_view = "login_view"
login_manager.init_app(app)
init.py:
from app import app, db, login_manager
import models
import views
My views.py has no import errors when I just run it using 'python views.py' and the route for '/' is identical to the hello world app. So I think there is a problem with app.py, init.py, or the fact that my routes aren't in the app.py file.
The problem might have been that the views are not imported in app.py or init.py, so are unknown to the application. Thus the CGI script threw the URL not found.
I'm learning Blueprints for Flask, but I am having trouble with importing the correct modules. This is my setup:
Folder structure:
- app.py
templates/
nomad/
- __init__.py
- nomad.py
app.py
from flask import Flask
from nomad.nomad import nblueprint
app = Flask(__name__)
app.register_blueprint(nblueprint)
nomad.py
from flask import render_template, Blueprint, abort
from app import app
nblueprint = Blueprint('nblueprint', __name__, template_folder='templates')
# Routes for this blueprint
#app.route ....
__init__.py is empty
The error I'm getting: ImportError: cannot import name nblueprint. I know my import statement is probably wrong, but what should it be and why?
EDIT:
If I remove from app import app, then I can successfully import nblueprint in app.py. But I need app in nomad.py because it needs to handle routes. Why is that line causing issues with importing, and how would I get around this?
Blueprints is for define application route so you don't need to use app instance and blueprint in same place for route defination.
#nomad.py
#nblueprint.route('/')
You are getting error because while you register the blueprint at the same time you use app instance. So as you said when you remove the from app ... it solve the problem.
The recommend way is define your view for that blueprint in blueprint package in your example nomad package, it should be like this:
...
nomad/
__init__.py
views.py
#nomad/__init__.py
nblueprint = Blueprint(...)
#nomad/views.py
from . import nblueprint
#nblueprint.route('/')
...
I built this app a few months ago on the flask server and it was working perfectly. I have uploaded all files into the right directories but I keep getting an Unhandled Exception saying there is No module named app.
Here is my structure:
/static/
(all static files)
/templates/
(all html files)
myapp.py
In myapp.py:
from app import app
from flask import render_template, redirect, request, url_for
#index - Home page containing images for the trailer, discussion thread and cast
#app.route('/')
#app.route('/index')
def index():
page_info = {
'title':'Star Wars - Forums',
}
img1 = 'pan.jpg'
img2 = 'trailerlink.jpg'
img3 = 'trailerdiscussion.jpg'
img4 = 'episode7cast.jpg'
return render_template('index.html', info=page_info, imgone=img1, imgtwo=img2,imgthree=img3, imgfour=img4)
In my wsgi.py file:
import sys
# add your project directory to the sys.path
project_home = u'/home/myusername'
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 myapp import app as application
And finally some of the errors in my error log:
File "/bin/user_wsgi_wrapper.py", line 122, in __call__ app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 136, in import_error_application
raise e
ImportError: No module named app
It's probably just something small, it usually is, but I can't seem to find it. Can anyone help?
It looks like you're trying to refer to your project as a package. You need to actually create a package called "app" if you want to do from app import app.
myproject/
app/
__init__.py # contains `app` object
views.py # was called myapp.py, does `from app import app`
static/
templates/
wsgi.py # does `from app import app as application`
In this case the Flask app should be defined in __init__.py so that importing it from the myapp modules works. Realistically, this naming scheme makes no sense, it looks like myapp.py should really be called views.py.
I would like to deploy my application which works fine on my local unix server to OpenShift cloud. I registered there and checkout git repository. But I don't know what to do now.
Application in this repository has following structure:
/libs
/app.py
/setup.py
/wsgi
static/
application
but I don't know where I should copy my project in which files should be modified. My project structure is following
/domain.wsgi
/domain/
app.py
infrastructure.py
models/
static/
templates/
views/
domain.wsgi
import sys, os
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)
from domain.app import app as application
app.py
from infrastructure import app
import views.index
import views.login
import views.logout
import models.sa
infrastructure.py
from flask import Flask, g
from flask.ext.sqlalchemy import SQLAlchemy
from models.sa import get_user_class, UserQuery
from models.database import db_session
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://.............'
db = SQLAlchemy(app)
## Set SQL Alchemy to automatically tear down
#app.teardown_request
def shutdown_session(exception=None):
db_session.remove()
# Instantiate authentication
User = get_user_class(db.Model)
# config
app.config.update(
DEBUG = True,
SECRET_KEY = 'xxxxxxxxx'
)
Thanks
You files go under wsgi folder; please see this tutorial on how to deploy flask applications to OpenShift: http://www.paasmag.com/2013/01/08/beginners-guide-to-writing-flask-apps-on-openshift/
I have a small Flask app which uses MongoEngine.
my project structure:
/myproject
-application.py
-config.py
/my_app
-models.py
-views.py
my application.py:
#!/usr/bin/env python
from flask.ext.mongoengine import MongoEngine
from config import app
import os
app.debug = True
# get config settings
if __name__ == '__main__':
app.config.from_object('config')
else:
app.config.from_object('heroku_config')
# wrap app in mongengine
db = MongoEngine(app)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
my models.py:
from application import db
from flask import url_for
# declare model classes
...
I am deploying on heroku. If my Procfile reads:
web: python application.py
It works fine. When I try to switch to Gunicorn:
web: gunicorn application:app
When I start gunicorn it complains by way of an import error:
ImportError: cannot import name db
Why is this an issue now? I'm guessing it's a path problem but I can't see why so.
I assume you're registering blueprints or something like that in application.py, which in turn imports the model, right?
You didn't supply the view file or how you're using the view file and if my guess isn't correct my answer below won't be either.
If my guess is correct it is probably because of a circular import.
You could create a db.py file that contains these lines (move from application.py):
from flask.ext.mongoengine import MongoEngine
db = MongoEngine(app)
and then import that file into your models (from db import db).
That means the flow would look something like this: db -> model -> view -> app instead of app (db) -> model -> view -> app.
Circular imports creates all kinds of annoying problems, try to avoid them whenever possible.
If you are using an init style flask module then the following works (derived from the pallet flask tutorial v Flask 2.0.1).
https://www.palletsprojects.com/p/flask/
web: env FLASK_APP=flaskr gunicorn -b '0.0.0.0':${PORT} 'flaskr:create_app()'
Where create_app is the "app" called from
flaskr/init.py