Call local host server with parameters - flask

I am running the Flask server on port 81. I want my server to show a normal page at / and a debug page at /debug. When I enter localhost:81 I get the normal page. When I try to navigate to localhost\debug:81 or localhost/81:81 I get a "Not Found" error. What am I doing wrong?
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/debug')
def index_debug():
return render_template('index.html', debug=true)

You have to have the project structure like this:
index.py
templates/
index.html
and your param debug has to be debug=True

Related

Why does my Flask base URL not work in Google App Engine?

I'm working on a project right now that I'm deploying to Google App Engine. I've almost got everything working except for one thing. I can't get the base URL to work.
I'm using Flask and flask-restx to build an API. I've configured flask-restx to display the swagger documentation when accessing the url something.ey.r.appspot.com/api/and serve the API endpoints from the url something.ey.r.appspot.com/project-api/. All of these endpoints work as expected. However, I want to serve a static html file at the base url of the application. For test purposes I have changed that to a simple "Hello World". Below you can see my Script in main.py
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
api = Api(app,
version='0.1',
title='Project API',
description='An API to access the System',
authorizations=authorizations,
doc='/api/'
)
#app.route('/')
def home():
return 'Hello World'
project_api = api.namespace('project-api', description='Project API')
#project_api.route('/projects')
#project_api.doc(security='Api-Key')
#project_api.doc(responses={200: 'Success', 400: 'Invalid Argument', 401: 'Unauthorized', 500: 'Internal Server Error'})
class ProjectListOperations(Resource):
def get(self, *args, **kwargs):
sys = ProjectSystem()
projects = sys.get_all_projects()
return projects
if __name__ == '__main__':
app.run(debug=True)
When running this code locally, everything works fine. I can see "Hello World" when accessing localhost:5000/ and all API-Endpoints and swagger documentation work. However, when deployed to Google App Engine, the base URL with the "Hello World" doesn't load. It instead returns Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. For reference, my app.yaml looks like this:
runtime: python39
handlers:
- url: /.*
script: main.py
Has anybody experienced this before and knows a solution for this?
Thanks in advance,

Flask Internal server error when rendering static files

I am new to Flask and I am encountering a problem: when I return a message, such as:
app_setup.py
#app.route("/")
def hello():
return '''Hello World!'''
it works fine. However, when I try to render a static html file such as:
app_setup.py
#app.route("/")
def hello():
return render_template('static/index.html')
it gives me an Internal Server Error. How can i fix this?
N.B: I am running Flask with uWSGI and Nginx in Docker.
main.py
from flask import *
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
from .core import app_setup
if __name__ == "__main__":
# Only for debugging while developing
app.run(host='0.0.0.0', debug=True, port=80)
Templates typically come out of a templates/ subdirectory of the app, which is where render_templates() looks for them. (Things get slightly more complicated when you're using blueprints, but safe that thought, since you aren't.)
Create a templates directory, and move index.html there. Then
return render_template('index.html')
By default, the render_templates() go look for your static template file into the /templates subdirectory of your app. A good approach would be to create a templates directory, and move the static index.html there.
Although, if you do want to set a new directory to template static files, you could try the following when initializing the app:
import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
# ...
app = Flask('myapp', template_folder=tmpl_dir)

requests.get does not response in python?

I have the following script which I tried to get response status from request.get(url)
from flask import *
import requests
app = Flask(__name__)
#app.route('/')
def home():
r = requests.get('http://127.0.0.1:5000/welcome')
print r
return render_template('home.html')
#app.route('/welcome')
def wecome():
print "welcome page"
return "welcome to my page"
if __name__=='__main__':
app.run(debug=True)
When I access endpoint http://127.0.0.1:5000/ the browser keeps spinning none stop without any output result in terminal console as I expected even the error message.
However, if I change the requests url to something else externally as below, the response is showing up the status <Response [200]> in terminal and the page is loaded as normal.
from flask import *
import requests
app = Flask(__name__)
#app.route('/')
def home():
r = requests.get('https://api.github.com/emojis')
print r
return render_template('home.html')
#app.route('/welcome')
def wecome():
print "welcome page"
return "welcome to my page"
if __name__=='__main__':
app.run(debug=True)
what's going on with that?
How can I get response from internal url as I need it badly for my current work?

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

Openshift vs localhost errors and error handling

I can run the code below both locally and on openshift with success, but with very different results. When I load '/' in both browsers I see that the code is working.
When I load '/main' in the browser it works locally, and it throws a 500 error(with no debug information) in openshift.
when I load '/error' in the browser I get debug information locally, and just 500 again in openshift.
How can I see debug information instead of a useless error message on openshift?
import watercore
from flask import Flask
app = Flask(__name__)
#app.errorhandler(404)
def page_not_found(e):
return '404'
#app.errorhandler(500)
def errorhandle(e):
return '500'
#app.route('/error')
'force a 500 error'
def testerrors(e):
return watercore.thisdefinitiondoesntexist()
#app.route('/')
def index():
return 'working'
#app.route('/main')
def mainpage():
return watercore.listall()
#app.route('/site/<sitename>')
def site(sitename):
if watercore.listall(sitename) == True:
return sitename
if __name__ == '__main__':
app.debug = True
app.run()
Openshift probably runs your app using wsgi, so your main is never run. To enable debug set the it outside if __name__ == '__main__':.
def create_app():
app = Flask(__name__)
app.debug = True
return app
app = create_app()
Note that you should never do this for an actual production app.
I found this on the flask quickstart:
Attention
Even though the interactive debugger does not work in forking
environments (which makes it nearly impossible to use on production
servers)
Which leads me to believe that the debugger will not work on openshift at all.
I've already switched to django!