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!
Related
I migrated from google.appengine.ext.webapp and ran into an issue with webapp2.WSGIApplication. I am using Django as the backend
the main part looks like this
application =webapp2.WSGIApplication([
('/warmup', warmupHandler)
('/api/layer', LayerService),
debug=False)
def main():
google.appengine.ext.webapp.util.run_wsgi_app(application)
if __name__ == '__main__':
main()
I have tried using this code snippet provided by google cloud as a replacement and it did no help.
def wsgi_middleware(app):
client = ndb.Client()
def middleware(request):
with client.context()
return app(request)
return middleware
They also have code snippits but i think this is for Flask, and i use django
def ndb_wsgi_middleware(wsgi_app):
def middleware(environ, start_response):
with client.context():
return wsgi_app(environ, start_response)
return middleware
In the current setup I have, all I get is a 404 error. Meaning its not picking up the templates
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
This simple web service works if I run it by hand but in my unit tests I get a 404 not found page as my response, preventing me to properly test the application.
normal behavior:
Folder structure:
/SRC
--web_application.py
/UNIT_TESTS
--test_wab_application.py
web_application.py
from flask import Flask, request, jsonify, send_from_directory
from python.Greeting import Greeting
application = Flask(__name__)
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='mega_developer',
DATABASE=os.path.join(app.instance_path, 'web_application.sqlite'),
)
try:
os.makedirs(app.instance_path)
except OSError:
pass
return app
#application.route('/greetings', methods=['GET', 'POST'])
def hello():
# GET: for url manipulation #
if request.method == 'GET':
return jsonify(hello = request.args.get('name', 'world', str))
test_web_application.py
import tempfile
import pytest
import web_application
class TestWebApplication:
app = web_application.create_app() # container object for test applications #
#pytest.fixture
def initialize_app(self):
app = web_application.create_app()
app.config['TESTING'] = True
app.config['DEBUG'] = False
app.config['WTF_CSRF_ENABLED'] = False
app.config['DATABASE'] = tempfile.mkstemp()
app.testing = True
self.app = app
def test_hello_get(self, initialize_app):
with self.app.test_client() as client:
response = client.get('/greetings?name=Rick Sanchez')
assert response.status_code == 200
test results (most relevant part only):
Launching pytest with arguments test_web_application.py::TestWebApplication::test_hello_get in C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\UNIT_TESTS
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-5.2.2, py-1.8.0, pluggy-0.13.0 -- C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\VENV\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Xrenyn\Documents\Projekte\Studium_Anhalt\QA&Chatbots Exercises\Exercise 2 - Web Service Basics\UNIT_TESTS
collecting ... collected 1 item
test_web_application.py::TestWebApplication::test_hello_get FAILED [100%]
test_web_application.py:21 (TestWebApplication.test_hello_get)
404 != 200
Expected :200
Actual :404
So far I have tested various alternative routing paths for the client.get() method in test-web_application.py , including combinations like '/SRC/greetings?name=Rick Sanchez' or '../SRC/greetings?name=Rick Sanchez', but all to no different effect.
Do you have any idea on what I might be doing wrong or how I could get access to my web services' functions from within unit tests?
I think the problem is that you are creating two Flask instances. One with the name application that you add hello route to, and the second one using the create_app function. You need to create a test client using the application instance (the one you added the hello route to).
Can you import application and then obtain the client using application.test_client()?
Sample solution:
import pytest
from web_application import application
#pytest.fixture
def client():
with application.test_client() as client:
yield client
class TestSomething:
def test_this(self, client):
res = client.get('/greetings?name=Rick Sanchez')
assert res.status_code == 200
Checkout the official docs on testing.
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
I created two flask apps: frontend and restapi (with flask-restful). I created the following runserver.py to run them in development:
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
from restapi import app as restapi_app
from frontend import app as frontend_app
application = DispatcherMiddleware(frontend_app, {
'/api': restapi_app,
})
if __name__ == "__main__":
run_simple(
'localhost',
5000,
application,
use_reloader=True,
use_debugger=True,
use_evalex=True)
Despite having use_debugger=True, whenever one of the flask-restful resources raises an error, I don't get a trace, just a 500 error
{"status": 500, "message": "Internal Server Error"}
Any ideas how to get the full trace to display? Let me know if you need more details/code.
use_debugger option of Werkzeug WSGI server only enables embedded debugger, the server is unaware of Flask app configuration values (DEBUG in this case). To propagate exceptions to the server, you need to enable debug mode for both Flask app objects yourself. Here's one way to do it:
if __name__ == '__main__':
restapi_app.debug = True
frontend_app.debug = True
run_simple(...)