How do I run flask app directly to 0.0.0.0/input page instead of "/"?
Is this possible?
Otherwise, what is best way to exclude "/" from showing?
#app.route("/")
def home():
return 200
if __name__ == '__main__':
app.run(host='0.0.0.0/input', port=int(os.getenv("FLASK_PORT", "8100")), debug=True)
Redirect your root url:
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route("/")
def home():
return redirect(url_for("hello"))
#app.route("/hello")
def hello():
return "<p>Hello</p>"
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
Related
I would like to call the create_app method from my run.py and then use it to start a Flask server. However, when I try this it does not start and no output appears in the console. Can someone help me with this?
main.py
from flask import Flask
from flask_restx import Api
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
def create_app():
app = Flask(__name__, static_url_path='/',static_folder='./UI/client/build')
bootstrap = Bootstrap(app)
app.config.from_object('settings')
app.secret_key = os.urandom(24)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
csrf = CSRFProtect(app)
CORS(app)
JWTManager(app)
api=Api(app,doc='/docs')
#app.route('/')
def index():
return app.send_static_file('index.html')
#app.errorhandler(404)
def not_found(err):
return app.send_static_file('index.html')
return app
run.py
from main import create_app
app=create_app()
With the following code I was able to start flask:
if __name__ == '__main__':
app = create_app()
app.run()
I am refreshing my browser...after running but,
changes are not affected in browser
from flask import Flask, send_file, render_template, send_file
app = Flask(__name__)
#app.route('/')
def hello_world():
return send_file('templates/create_conf_view.html')
if __name__ == '__main__':
app.run(debug=True, use_reloader=True, host='0.0.0.0', port=1672,threaded=True)
What i am doing wrong ?
According to your code you need to have a directory structure as follows:
app
|_
run.py
templates/
|_create_conf_view.html
According to docs you should not pass templates when rendering a template.
Change your original file to and see if it works:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('create_conf_view.html')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=1672, thread=True)
Also be sure to access your application at specified port!
I deployed a very simple Flask application called 'app' in a sub directory under root directory in Bluehost. Hopefully, example.com points to the homepage and example.com/app points to my Flask application. Actually, the Flask application works pretty fine when the script index.py looks like:
from flask import Flask
app = Flask(__name__)
#app.route('/', methods=['GET'])
def home():
return 'Hello world'
if __name__ == "__main__":
app.run()
But things went bad as I introduced a simple login functionality, with the doc structure and index.py look like:
doc structure:
public_html
|--app
|--.htaccess
|--index.fcgi
|--index.py
|--static
|--login.html
|--templates
|--home.html
index.py:
from flask import Flask, url_for, request, render_template, redirect, session
app = Flask(__name__)
#app.route('/', methods=['GET'])
def home():
if not session.get('user'):
return redirect(url_for('login')) #go to login page if not logined
else:
return render_template('home.html') #otherwise go to home page
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return app.send_static_file('login.html')
else:
user = request.form.get('user')
password = request.form.get('password')
if user == 'joy' and password == 'joy':
session['user'] = user
return render_template('home.html')
else:
return 'LOGIN FAILED'
if __name__ == "__main__":
app.run()
However, accessing example.com/app led to a changed URL as example.com/login and a reasonable 404 error as example.com/login doesn't map to any document.
return redirect(url_for('login'))
The url_for('login') return example.com/login instead of example.com/app/login. That's why the latter version of index.py doesn't work. I tried so many things but didn't came across any fix. Please help. THanks!
My .htaccess:
Options +ExecCGI
AddHandler fcgid-script .fcgi
RewriteEngine On
#RewriteBase /app/ # Neither RewriteBase / or RewriteBase /app/ work
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
My index.fcgi:
import sys
sys.path.insert(0, '/path_to_my_python_site-packages')
from flup.server.fcgi import WSGIServer
from index import app
class ScriptNameStripper(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['SCRIPT_NAME'] = ''
return self.app(environ, start_response)
app = ScriptNameStripper(app)
if __name__ == '__main__':
WSGIServer(app).run()
The following works for me now.
Comment RewriteBase in .htaccess
Updated index.py with a customized url_for
from flask import Flask, redirect, url_for
app = Flask(__name__)
def strip_url(orig):
return orig.replace('index.fcgi/', '')
#app.route('/', methods=['GET'])
def home():
return redirect(strip_url(url_for('login')))
#app.route('/login', methods=['GET'])
def login():
return 'please login'
if __name__ == "__main__":
app.run()
If a conclusion has to be made, I would like say official Flask fastcgi docs demands a RewriteRule to remove the ***.fcgi from the url which doesn't work for redirect initiated from within code.
Set APPLICATION_ROOT in your Flask config:
app.config["APPLICATION_ROOT"] = "/app"
Don't use RewriteBase, Flask needs to know about the URL root to generate URLs.
I want to open index.html,
But can not find pic.html
How could i do
pic.html and index.html are all in the templates
index.html
<body>
<iframe src="pic.html"></iframe>
</body>
flaskdemo.py
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run()
Flask doesn't serve files from its templates directory. You would need to set up a route for /pic.html and render the appropriate template as part of that:
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template("index.html")
#app.route('/pic.html')
def pic():
return render_template("pic.html")
if __name__ == '__main__':
app.run()
from flask import Flask, render_template
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/page/<path:page>')
def article(page):
return render_template('page.html')
if __name__ == "__main__":
app.run()
Work just fine. But if i change the second route to #app.route('/<path:page>'), then any access to URL like /path/to/page yields 404.
Why doesn't #app.route('/<path:page>') work?
Related questions, that don't answer the question however:
Flask: Handle catch all url different if path is directory or file
Custom routing in Flask app
Capture arbitrary path in Flask route
static_url_path conflicts with routing. Flask thinks that path after / is reserved for static files, therefore path converter didn't work. See: URL routing conflicts for static files in Flask dev server
works flawless for me:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/page/<path:page>')
def article(page):
return render_template('page.html')
if __name__ == "__main__":
app.debug = True
app.run()
I can access: http://localhost/ -> index and http://localhost/page/<any index/path e.g.: 1> -> article