I'm not able to run flask successfully
When i execute the apps_server.py..it stop initialized as follow
Serving Flask app "apps_server" (lazy loading) Environment:production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
Debug mode: on
It just stuck at that point...and there is no Running on http://localhost:5000/ line show up...
May I know what could be the problem?
This is snippet of the code
from flask import Flask, render_template, Markup, request, jsonify
from flask.helpers import send_file
import os,httplib,json,subprocess
import flask
from flask import request, jsonify, abort, render_template, flash, redirect, url_for
import argparse, sys
import logging
import logging.config
from logging.handlers import RotatingFileHandler
from logging import Formatter
#app = flask.Flask(__name__)
app=Flask(__name__,template_folder='templates')
app.config["DEBUG"] = True
##Functions and code to execute##
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
Please advise further.
I got your code working by doing the following changes:
from flask import Flask, render_template, Markup, request, jsonify
from flask.helpers import send_file
import os,http.client,json,subprocess
import flask
from flask import request, jsonify, abort, render_template, flash, redirect, url_for
import argparse, sys
import logging
import logging.config
from logging.handlers import RotatingFileHandler
from logging import Formatter
app = Flask(__name__)
#app.route("/")
def home():
return "Hello World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Try now ;) Seems like it might have been the debugging. Also, make sure that the #app.route statement is correct. If you are using a template here and there is just a small mistake, it will not work. I am not sure if your code is correct inside what you call the ##Functions and code to execute##. Make sure that whatever you have inside here is correct. Python 3 also renamed httplib to http.client (ref here), so I changed this during the import. However, the code above is working for me.
Also, if you want to use a template (as you've indicated in the post), you can refer to the template as following:
#app.route("/", methods=["GET"])
def home():
return render_template("home.html")
Remember to make a directory called "templates", and put the home.html file there. Flask will automatically look for the "templates" directory.
Related
I've rummaged through maybe 50 different answers to this and still I haven't manage to fix it... I'm pretty new to flask and python.
I have an app which was running great locally but I've struggled with deploying on python anywhere. Initially I had a few import modules issues, now it runs but doesn't return any html template, despite not seeing any other issue. The main issue I had was that it couldn't find the "routes" app from wsgi, and I sort of fixed adding the app = Flask(name) line on routes.py (the short blueprint object is not callable).
routes.py:
from flask import Blueprint, render_template, request, redirect, send_file
import pyqrcode
from pyqrcode import QRCode
import subprocess
from extensions import db
from models import Link
app = Flask(__name__)
short = Blueprint('short', __name__, url_prefix='/')
#short.route('/index')
def index():
return render_template('index.html')
init.py
from flask import Flask
from extensions import db
from routes import short
def create_app(config_file='settings.py'):
app = Flask(__name__)
app.config.from_pyfile(config_file)
db.init_app(app)
app.register_blueprint(short)
return app
wsgi.py
import sys
# add your project directory to the sys.path
project_home = u'/home/b297py/mysite'
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 routes import app as application
For the purpose of testing, I've placed all the html templates both in the root directory and in the specific /template directory but it just didn't fix the issue.
In wsgi.py you are not calling create_app so you are never registering the blueprint. You should replace :
from routes import app as application
by something like :
from package_name import create_app
application = create_app()
(Example: https://www.pythonanywhere.com/forums/topic/12889/#id_post_50171)
Also as you mentioned, the fix adding app = Flask(__name__) to routes.pyallows you to bypass create_app (so you should remove it if you want to stick to the create_app approach).
In a Python authorization app, in my main py I have the following code:
# main.py
from flask import Blueprint, render_template
from flask_login import login_required, current_user
theapp = Blueprint('main', __name__)
#theapp.route('/')
def index():
return render_template('index.html')
When I try:
FLASK_APP=main.py
FLASK_DEBUG=1
flask run
I get the following error:
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
Basically a Blueprint is a way for you to organize your flask application into smaller and reusable applications. I am not sure why you have used it here in the main.py.
You could do that some other file, for example, you have a set of endpoints to implement login functionality in a separate file then what you should be doing is:
Assume you have a login.py .Sample Code looks like follows:
from flask import Blueprint
bp = Blueprint('login_bp', __name__)
def login_bp():
return bp
And the following code goes into you main.py , you need to start the Flask Server using .run()
from flask import Flask
from flask import Blueprint, render_template
from login import login_bp #Assume you have a module login and I am importing login_bp from login.py
theapp = Flask(__name__) #Creating Flask instance
theapp.register_blueprint(login_bp()) # Registering Blueprint here
#theapp.route('/')
def index():
return render_template('index.html')
theapp.run(host="0.0.0.0", port=2019, debug=True) #Starting the Flask Server
Hope this works, please do look out for documents and code example to get deeper insights.
I am trying to run a small flask modular application under windows 10. I have created a module to lunch the index page. While as a single application runs correctly and loads the home page, I cannot make it modular getting a 404 error page not found.
Here is my directory structure:
Application directory structure
My files:
runserver.py
import os
#from app.models import User, Role
from flask import Flask
basedir = os.path.abspath(os.path.dirname(__file__))
from landingpage import app
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
__init__.py
import os
from flask import Flask, render_template, session, redirect, url_for
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, TextField, DateField, SubmitField
from wtforms.validators import Required
from wtforms.fields.html5 import DateField
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin.form.widgets import DatePickerWidget
basedir = os.path.abspath(os.path.dirname(__file__))
#print "basedir is %r " % (basedir)
app = Flask(__name__)
import views
class AnotherSearchForm(Form):
place = StringField(default=u'Où voulez-vous aller?', validators=[Required()])
checkin =TextField(default=u'checkin', validators=[Required()])
checkout=TextField(default=u'checkout', validators=[Required()])
dt = DateField('DatePicker', format='%Y-%m-%d')
submit = SubmitField('Rechercher')
views.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Flask, render_template, session, redirect, url_for, current_app
#from .. import db
#from ..models import User
#from ..email import send_email
import landingpage
from landingpage import app
#from .forms import AnotherSearchForm
#app.route('/', methods=['GET', 'POST'])
def index():
form = AnotherSearchForm()
return render_template('indexnew.html',
title='Home',
form=form)
The application is running correctly as you see below,
$ python runserver.py
C:\Users\admin\Anaconda\lib\site-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
but is failing to load the home page indexnew.html on http://127.0.0.1:5000/ giving a 404 error:
127.0.0.1 - - [22/Apr/2016 14:10:21] "GET / HTTP/1.1" 404 -
You appear to have app defined in runserver.py as well as in your __init__.py
I suspect that runserver.py is running the app defined there, while your real application is actually being set up and then overridden by your runserver.py.
You want to import app within runserver.py and use that, rather than define it again.
In other words, remove this line from runserver.py...
app = Flask(__name__)
update
I've got a version of your code that has the fix I suggest. You can find it on GitHub:
https://github.com/martinpeck/stackoverflow_example_1
I took your code. It failed in two ways:
your import of views didn't work for me
once I'd fixed that, I saw the 404
To fix your code:
replace import views with import landingpage.views in __init__.py
as suggested above, remove app = Flask(__name__) from runserver.py
I'm attempting to break a small app into units and use the Blueprint pattern in Flask. However I seem to have trouble in getting the app running.
Here is my structure:
\myapp
login.py
\upload
__init__.py
views.py
Here is login.py:
import sys, os
from flask import Flask, Blueprint, request
from flask import render_template, session
from .upload import views
app = Flask(__name__)
app.register_blueprint(views)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
print app.url_map
print app.blueprints
app.run(debug = True)
for __init__.py
from flask import Flask
app.register_blueprint('upload', __name__)
and in views.py
from flask import Flask, Blueprint, request, redirect, url_for, render_template
import views
upload = Blueprint('upload', __name__)
#upload.route('/uploaded', methods=['GET', 'POST'])
def upload_file():
...
Looking at the logs on heroku, here is the error:
from .upload import views
2015-09-05T10:59:00.506513+00:00 app[web.1]: ValueError: Attempted relative import in non-package
Have a structured my package and blueprint correctly? I used the documentation, but I think I'm missing something here.
There are three problems with your code:
You are using a relative import in login.py to include views, but given the folder structure and the fact that you use login.py as starting point, it cannot work here. Simply use from upload import views instead.
The __init__.py references an unknown variable, app. You actually don't need anything in this file, remove everything.
You try to register a module as a blueprint via app.register_blueprint(views) in login.py. This cannot work, a module is not a blueprint. Instead, import the upload variable defined in the views module, that is a blueprint: app.register_blueprint(views.upload).
Changing that should get you started. Two side notes:
You have an import in views.py that should probably not be there: import views. This should be harmless however.
I answered a question about Flask blueprints some days ago, and gave an example about how to use them. Maybe would you find the answer useful in your case as well (in particular the part where the blueprint definition is moved to the __init__.py file defining the blueprint).
I have been following the methods provided in this post:
https://stackoverflow.com/questions/12167729/flask-subdomains-with-blueprint-getting-404
Here is my relevant code:
__init__.py
from flask import Flask, render_template
app = Flask(__name__, static_url_path="", static_folder="static"
import myApp.views
views.py
from flask import Flask, render_template, request, Blueprint
from myApp import app
app.config['SERVER_NAME'] = 'myapp.com'
app.url_map.default_subdomain = "www"
#app.route("/")
def index():
return "This is index page."
test = Blueprint('test', 'test', subdomain='test')
#test.route("/")
def testindex():
return "This is test index page."
app.register_blueprint(test)
if __name__ == "__main__":
app.run()
Using this method I am able to get subdomains 'test' and 'www' working, but now I am unable to access my website via IP address.
Any guidance into the right direction would be appreciated!