I have a python script (script.py) that when I run it in the console it keeps receiving data in JSON format, now I want to visualize the output of the console on a web page or to be able to execute the script.py and capture the output to view in the browser, from what I have read I understand that with FLASK I could do it, an example or guide to achieve it.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def code():
out = open(r'output.py', 'r').read()
return exec(out)
if __name__ == '__main__':
app.run(host='0.0.0.0')
///////////////////////////////////////////////
builtins.RuntimeError
RuntimeError: There is no current event loop in thread 'Thread-9'.
Traceback (most recent call last)
File "..//python3.6/site-packages/flask/app.py", line 2301, in __call__
return self.wsgi_app(environ, start_response)
File "..//python3.6/site-packages/flask/app.py", line 2287, in wsgi_app
response = self.handle_exception(e)
File "..//python3.6/site-packages/flask/app.py", line 1733, in handle_exception
reraise(exc_type, exc_value, tb)
File "..//python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "..//python3.6/site-packages/flask/app.py", line 2284, in wsgi_app
response = self.full_dispatch_request()
File "..//python3.6/site-packages/flask/app.py", line 1807, in full_dispatch_request
rv = self.handle_user_exception(e)
File "..//python3.6/site-packages/flask/app.py", line 1710, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "..//python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "..//python3.6/site-packages/flask/app.py", line 1805, in full_dispatch_request
rv = self.dispatch_request()
File "..//python3.6/site-packages/flask/app.py", line 1791, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/share/server/www/test/index1.py", line 9, in dynamic_page
return exec(file)
File "<string>", line 60, in <module>
///////////////////////////////////////////////////////////////////////////
output.py
#!/usr/bin/env python3
import json
import sys
from phone import Runn, BReporter, EventHandler
class NoOpEventHandler(EventHandler):
def on_event(self, event):
self._reporter.on_event(event)
class VerboseNoOpEventHandler(NoOpEventHandler):
FILTER_EVENTS = False
class JsonReporter(BReporter):
def __init__(self):
self._has_first_line = False
def on_event(self, event):
json_data = json.dumps(dict(event), sort_keys=True)
if self._has_first_line:
sys.stdout.write(',')
else:
sys.stdout.write('[')
self._has_first_line = True
sys.stdout.write('\n {}'.format(json_data))
def close(self):
sys.stdout.write('\n]')
reporter = JsonReporter()
runner = Runn([
'tcp://test123:test123#127.0.0.1:5038',
], reporter, handler=NoOpEventHandler)
runner.run()
just use this; you must set debug = True. You do not have to provide host for testing.
if __name__ == "__main__":
app.run(debug=True)
you should see an output like that on terminal;
* Serving Flask app "my_flask_app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: xxx-xxx-xxx
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
open a web browser and copy paste: http://127.0.0.1:5000/
I saved your code in tmp.py and just ran it as python tmp.py.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def code():
out = open(r'output.py', 'r').read()
return exec(out)
if __name__ == '__main__':
app.run(debug = True)
run it as below:
(flaskvenv) C:...>python tmp.py
Here is the output:
* Serving Flask app "tmp" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
That means the code runs. You might have another problem!
I think the problem is with the exec(out) . Actually , exec is a dynamic execution of a program which can either be a string or object code, and it does not return anything , it just executes a program and returns None.
If you run your code without trying to return the exec(out) you won't get error.
Related
I am using python 3.9.6 with ninja2 and blueprint.
py --version
returns:
Python 3.9.6
As far as I know, blueprint is a seperate folder, with seperate html templates and static files (css/js) , and I can have many blueprints in one runnable python project.
I have looked at Views with Jinja2 and blueprint
The hierarchy of the html+relevant files of myblueprint is:
main_project -> myblueprint -> templates -> myblueprint.html
-> static -> myblueprint.css
-> myblueprint.js
The relevant code:
import os
from flask import Flask, Blueprint, redirect, request, render_template, url_for, session
main_page = Blueprint('myblueprint', __name__)
#main_page.route("/myblueprint")
def home():
query = 'select * from users;'
users = interact_db(query=query, query_type='fetch')
return render_template('myblueprint.html')
...
#app.route('/', methods=['GET'])
def main():
return redirect("myblueprint")
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.secret_key = '12345'
app.run(host='0.0.0.0', port=port)
For some reason, when I run: https://localhost:5000, I get an error:
ERROR in app: Exception on /myblueprint [GET] Traceback (most recent
call last): File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 2073, in wsgi_app
response = self.full_dispatch_request() File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1518, in full_dispatch_request
rv = self.handle_user_exception(e) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1516, in full_dispatch_request
rv = self.dispatch_request() File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:/main_project/myproject/app.py", line 17, in home
return render_template('myblueprint.html') File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 148, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list), File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 997, in get_template
return self._load_template(name, globals) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals)) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\loaders.py",
line 125, in load
source, filename, uptodate = self.get_source(environment, name) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 59, in get_source
return self._get_source_fast(environment, template) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 95, in _get_source_fast
raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: myblueprint.html
127.0.0.1 - - [04/Jan/2022 08:04:31] "GET /myblueprint HTTP/1.1" 500 -
127.0.0.1 - - [04/Jan/2022 08:04:31] "GET /favicon.ico HTTP/1.1" 404 -
I have also noticed that on the chrome network console (not in code run window), I see another exception:
Request URL: http://localhost:5000/
Request Method: GET
Status Code: 500 INTERNAL SERVER ERROR
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
What is the cross origin for blueprint, and how can I avoid that?
What is wrong in my code above, and should I fix the heirarchy?
Two problems in your code. First you have to register your blueprint
import os
from flask import Flask, Blueprint, redirect, request, render_template, url_for, session
app = Flask(__name__)
main_page = Blueprint('myblueprint', __name__)
#main_page.route('/myblueprint', methods=['GET'])
def home():
query = 'select * from users;'
users = interact_db(query=query, query_type='fetch')
return render_template('myblueprint.html')
#app.route('/', methods=['GET'])
def main():
return redirect("myblueprint")
app.register_blueprint(main_page)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5800))
app.secret_key = '12345'
app.run(host='0.0.0.0', port=port)
Then your html file must simply be in the templates folder:
> templates > myblueprint.html
This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 3 years ago.
I am trying to run a simple flask application in which it only prints hello world but i am having a type error. In the type error there is a trackback which is specifying a file named app.py and showing errors in it but i can't figure them out. The file in which i am having error is in the flask folder.Please help me that how i can resolve this problem.
I have already done running these code due to which the command prompt gives me the localhost code but when i tried to run it on the browser i am having the type error .
set FLASK_ENV=development
set FLASK_APP=app.py
This is my code
from flask import Flask
app = Flask("__name__")
#app.route("/")
def index():
print("Hello World")
When i run these three lines on my command prompt
set FLASK_ENV=development
set FLASK_APP=app.py
flask run
**i receive this **
Serving Flask app "app.py" (lazy loading)
Environment: development
Debug mode: on
Restarting with stat
Debugger is active!
Debugger PIN: 179-513-092
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
after this when i use the code in my browser the browser shows me this
Traceback (most recent call last):
File "c:\users\muhammad umar\appdata\local\programs\python\python37- 32\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "c:\users\muhammad umar\appdata\local\programs\python\python37- 32\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1967, in finalize_request
response = self.make_response(rv)
File "c:\users\muhammad umar\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2097, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
You're not supposed to print the response, you need to return it, so that Flask can send it to the browser:
from flask import Flask
app = Flask("__name__")
#app.route("/")
def index():
return "Hello World"
This is not to say that you cannot print, you can (it shows up in the console), but remember to return a response in your routes.
You don't need to 'print' the output but need to 'return' it. So changed code will be :
from flask import Flask
app = Flask("__name__")
#app.route("/")
def index():
return "Hello World"
I'm very new to python programming, I'm trying to expose few terminal commands as a http call. I'm packaging this below code into a tar.gz using setup.py and extracting this on the server to run the code in nginx web server. once I instantiate the app.py code using below, the http calls work fine for few hours. Not sure what happens after that, the http pages show an error and I do see the app is running in the server. Can someone please help me with this
gunicorn --bind 0.0.0.0:8000 cstaradmin:app &
#!/usr/bin/env python
from flask import Flask
from shelljob import proc
from flask import Response
from flask import json,jsonify
def get_pretty_print(json_object):
return json.dumps(json_object, sort_keys=False, indent=4, separators=('\n',' '))
def read_process(g):
while g.is_pending():
lines=g.readlines()
for proc,line in lines:
yield line
app = Flask(__name__)
def has_no_empty_params(rule):
defaults = rule.defaults if rule.defaults is not None else ()
arguments = rule.arguments if rule.arguments is not None else ()
return len(defaults) >= len(arguments)
#app.route('/', methods = ['GET'])
def help():
"""Print available functions."""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list)
#app.route("/ps")
def IRR():
IRR = ["ps"]
g=proc.Group()
p=g.run(IRR)
return Response(read_process(g),mimetype= 'text/plain')
def catch_all(path):
return
if __name__ == "__main__":
try:
app.run(host='0.0.0.0',port=8000)
except:
pass
Error:
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application
[2016-10-22 15:38:55,505] ERROR in app: Exception on /path/ToMy/command [GET]
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/path/ToMyapp/admin/cstaradmin.py", line 42, in listnodes
p=g.run(listnodes)
File "/usr/lib/python2.7/site-packages/shelljob/proc.py", line 53, in run
CommandException( e, "Group.run '{}' failed".format( cmd ) ).do_raise()
File "/usr/lib/python2.7/site-packages/shelljob/proc.py", line 51, in run
return self._run_impl( cmd, shell )
File "/usr/lib/python2.7/site-packages/shelljob/proc.py", line 63, in _run_impl
stdin = subprocess.PIPE, # needed to detach from calling terminal (other wacky things can happen)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1216, in _execute_child
errpipe_read, errpipe_write = self.pipe_cloexec()
File "/usr/lib64/python2.7/subprocess.py", line 1168, in pipe_cloexec
r, w = os.pipe()
CommandException: ("Group.run '['nodetool', ' status']' failed", OSError(24, 'Too many open files'))
I'm running into an issue trying to run my python web app on EB. It runs fine locally, but I get the following exception when I run it on EB. The problem seems to be that it runs into an exception, but the stack trace is of an error that occurs after that original one, so I can't really determine what the root cause is:
Exception on /admin GET
Traceback (most recent call last):
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionshttp://rule.endpoint(**req.view_args)
File "/opt/python/run/venv/lib/python2.7/site-packages/sandman/sandman.py", line 459, in get_collection
cls = endpoint_class(collection)
File "/opt/python/run/venv/lib/python2.7/site-packages/sandman/sandman.py", line 185, in endpoint_class
cls = current_app.class_referencescollection
File "/opt/python/run/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'Flask' object has no attribute 'class_references'
When I manually start the app on port 5000 after SSHing into my instance, and attempted to load the same page from the console, I did not get any error (and the saved file contained the correct HTML):
wget http://127.0.0.1:5000/admin
--2014-03-23 17:01:13-- http://127.0.0.1:5000/admin
Connecting to 127.0.0.1:5000... connected.
HTTP request sent, awaiting response... 127.0.0.1 - - 23/Mar/2014 17:01:13 "GET /admin HTTP/1.1" 301 -
301 MOVED PERMANENTLY
Location: http://127.0.0.1:5000/admin/ following
--2014-03-23 17:01:13-- http://127.0.0.1:5000/admin/
Connecting to 127.0.0.1:5000... connected.
HTTP request sent, awaiting response... 127.0.0.1 - - 23/Mar/2014 17:01:13 "GET /admin/ HTTP/1.1" 200 -
200 OK
Length: 1519 (1.5K) text/html
Saving to: ‘admin’
this is the python app code I'm running: http://pastebin.com/qgnWz6aK
I managed to work around this issue by using Tornado (though I'm still not sure what the underlying issue is):
from sandman import app
from sandman.model import activate
import logging
import os, sys
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB']
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
activate(browser=False)
app.debug = True
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(os.environ['PORT'])
IOLoop.instance().start()
I was not able to implement a working minimal example with the Python Micro-Webframework Flask using a neo4j graphdatabase via the embedded python bindings (neo4j / python-embedded, version 1.6). What I have (on the basis of this Stack-Overflow-thread) is:
import os
import jpype
from neo4j import GraphDatabase
from flask import Flask, g
# configuration
DATABASE = 'graphdatabase'
DEBUG = True
SECRET_KEY = 'blubber'
USERNAME = 'tobias'
PASSWORD = 'bla'
ADMIN = 'admin'
app = Flask(__name__)
app.config.from_object(__name__)
def connectDB():
return GraphDatabase(app.config['DATABASE'])
def initDB():
db = connectDB()
with db.transaction:
users = db.node()
userIndex = db.node.indexes.create('users')
user = db.node(name=app.config['ADMIN'])
userIndex['name'][app.config['ADMIN']] = user
db.shutdown()
print "Database initialized."
#app.before_request
def before_request():
jpype.attachThreadToJVM()
g.db = connectDB()
#app.teardown_request
def teardown_request(exception):
jpype.attachThreadToJVM()
g.db.shutdown()
#app.route('/')
def index():
with g.db.transaction:
userIndex = g.db.node.indexes.get('users')
user = userIndex['name'][app.config['ADMIN']].single
username = user['name']
return render_template('index.html', name=username)
if os.path.exists(app.config['DATABASE']) == False:
initDB()
if __name__ == '__main__':
app.run()
Unfortunately, it throws:
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__
return self.wsgi_app(environ, start_response)
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/tobias/Esk/Dev/adhocracyLight/adhocracyLight.py", line 73, in index
userIndex = g.db.node.indexes.get('users')
File "/home/tobias/Esk/Dev/adhocracyLight/venv/lib/python2.7/site-packages/neo4j/index.py", line 36, in get
return self._index.forNodes(name)
java.lang.RuntimeExceptionPyRaisable: java.lang.IllegalArgumentException: No index provider 'lucene' found. Maybe the intended provider (or one more of its dependencies) aren't on the classpath or it failed to load.
I guess the problem is due to the threading (g is thread-local and contains a pointer to the neo4j-Database, maybe that's a bad idea?).
Neo4j Embedded is not intended to be used in a Web server environment -- you should use Neo4j Server and a Neo4j Server client.
Bulbs (http://bulbflow.com) is a Neo4j Server client that was designed with Flask in mind, in fact bulbflow.com is running on Flask on Heroku, using the Neo4j Heroku Add On (which is currently free).
You use Gremlin or Cypher for queries and transactional requests.
For an example of how to structure your app, see the Lightbulb (https://github.com/espeed/lightbulb) blog example, esp:
https://github.com/espeed/lightbulb/blob/master/lightbulb/model.py
https://github.com/espeed/lightbulb/blob/master/lightbulb/bulbsconf.py
Notice this line in bulbsconf.py:
bulbs_config.set_neo4j_heroku()
Lightbulb is designed to run on Heroku with the Neo4j Heroku Add On -- leave that line out if you are not running on Heroku.
Then in your Flask views or your app.py, do:
from bulbsconf import graph