Running python app on localhost - python

I'm trying to get a simple python script from the learnpythonthehardway tutorial to show up on my browser but keep encountering getting the following error:
$ python app.py
http://0.0.0.0:8080/
Traceback (most recent call last):
File "app.py", line 15, in <module>
app.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 310, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/httpserver.py", line 148, in runsimple
server.start()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/wsgiserver/__init__.py", line 1753, in start
raise socket.error(msg)
socket.error: No socket could be created
The script app.py is this:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == "__main__":
app.run()
What should I try now? It actually worked to print Hello World on my browser once, but I've been meddling with it and now it's giving me error messages regardless of what I try. I don't know what these messages mean or how to fix them.

The problem is due to the way web.py loading works, you need to have the creation and running of the app only occur if this is the main entry point of the program.
Otherwise, the class loader in web.py will reload this file again later, and wind up spawning a new server when its intent was simply to load a class.
try this
if __name__ == '__main__' :
app = web.application(urls, globals())
app.run()
Source: No socket could be created (other causes)

Changing the port address could fix this. Probably 8080 might be used for something else. Idk im speculating. The following fixed the issue for me.
try
$ python app.py 8081

Related

Error in deployment of Panel Dashboard(Python) on IIS server using Fast CGI

Error occurred while reading WSGI handler: Traceback (most recent call last):File "C:\ProgramData\Anaconda3\envs\Dashboard\lib\site-packages\wfastcgi.py", line 791, in mainenv, handler = read_wsgi_handler(response.physical_path)File "C:\ProgramData\Anaconda3\envs\Dashboard\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handlerhandler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))File "C:\ProgramData\Anaconda3\envs\Dashboard\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handlerhandler = getattr(handler, name) AttributeError: module 'main' has no attribute 'app' StdOut: StdErr
I have successfully deployed a Flask application on the same server by the help of this resource. But now I am getting the above error. Serving on local machine the code runs fine.
Please suggest if their is other way around for deploying panel application on IIS Server
My code for Panel Dashboard is as follows:( I have only included the important part of the code)
template3 = pn.template.FastListTemplate(
title='Production Dashboard',
logo='logo.jpg',
sidebar=[pn.pane.JPG('logo.jpg', sizing_mode='scale_both'),
pn.pane.Markdown("# "),
pn.pane.Markdown(
" "),
pn.pane.Markdown("### Settings"), month_slider, plant_selection],
main=[pn.Row(pn.Column(yaxis_section4, params_line_plot1.panel(width=700), margin=(0, 25)),
pn.Column(yaxis_params, params_table.panel(width=500))),
pn.Row(pn.Column(yaxis_params2, yaxis_section2, params_bar_plot.panel(width=300), margin=(0, 25))),
pn.Row(pn.Column(yaxis_section7, spc_plot1.panel(width=700), margin=(0, 25)),
pn.Column(yaxis_section6, spc_bar_plot.panel(width=300), margin=(0, 35)))],
accent_base_color="#0E4474",
header_background="#0E4474",
)
template3.servable();
if __name__ == "__main__":
template3.show()`

Import with and without main scope

I have two files, app.py and database.py in the same directory.
Primarily I have the following code snippets:
app.py
import database
db = "demo_database"
print(database.show_database_information())
database.py
from app import db
database_username = "root"
database_password = "password"
def show_database_information():
information = {}
information["filename"] = db
information["username"] = database_username
information["password"] = database_password
return information
When I try to run app.py I got the following error:
Traceback (most recent call last):
File "K:\PyPrac\circular_call\app.py", line 1, in <module>
import database
File "K:\PyPrac\circular_call\database.py", line 1, in <module>
from app import db
File "K:\PyPrac\circular_call\app.py", line 3, in <module>
print(database.show_database_information())
AttributeError: module 'database' has no attribute 'show_database_information'
Then I updated app.py and included __main__ check like below:
app.py
import database
db = "demo_database"
if __name__ == '__main__':
print(database.show_database_information())
Now it runs smoothly without any error.
I have several questions,
What is name of the error occurred in first scenario? Need explanation.
Why it runs after including __main__ scope?
What is the better approach of doing operations like this?
What I can understand are as below's. Maybe someone more expert can elaborate !
Import error.
if __name__ == '__main__': This condition is used to check whether a python module is being run directly or being imported.
If a module is imported, then it's __name__ is the name of the module instead of main. So, in such situations it is better to call if __name__ == '__main__':
Man!! You are creating a circular moment. Let me tell how.
import database # from app.py
But from database.py you imported db from app. That is creating a circular moment.
On the other hand,
if __name__ == '__main__':
this is making you database.py as a name of the module instead of __main__ that's why it's working. Nothing magical :)
UPDATE: Placed from app import db this line inside the function show_database_information()
This is the HOTFIX for you.

Flask Error with wsgi_handler

I am trying to use WSGI on Windows Server to run a simple flask app. I keep running into the following error:
Error occurred while reading WSGI handler: Traceback (most recent call
last): File "c:\inetpub\wwwroot\test_site\wfastcgi.py", line 711, in
main env, handler = read_wsgi_handler(response.physical_path) File
"c:\inetpub\wwwroot\test_site\wfastcgi.py", line 568, in
read_wsgi_handler return env, get_wsgi_handler(handler_name) File
"c:\inetpub\wwwroot\test_site\wfastcgi.py", line 551, in
get_wsgi_handler raise ValueError('"%s" could not be imported' %
handler_name) ValueError: "app.app" could not be imported StdOut:
StdErr
For my site I configured a handler to call the FastCGIModule from Microsoft Web Platform installer
My app file looks as such:
from flask import Flask, request, jsonify
from analyzers import analyzer
import write_log
app = Flask(__name__)
#app.route("/")
def test():
return "Test load"
#app.route('/analyze', methods=['POST'])
def parse():
text = request.json['text']
name = request.json['name']
model = request.json['model']
try:
convert_flag = request.json['convert_flag']
except KeyError:
convert_flag = False
results= analyzer(text, name, model, convert_dose=convert_flag)
write_log.write_log(text, name, model, results)
return jsonify(results)
if __name__ == "__main__":
app.run()
If I comment out the custom import of my analyzer script and my write_log script along with the POST method things will run, so I know I must be messing something up there.
Does anybody have any suggestions?
Thanks in advance.
Paul
I had the same issue and the problem was with a third-party library. What's causing your problem is certainly something different, but here's something I did to identify my issue and may help you as well:
Open wfastcgi.py
Locate the method get_wsgi_handler (probably on line 519)
There's a try/except inside a while module_name statement
Add raise to the end of the except block and save the file, like this:
except ImportError:
...
raise
Access your website URL again and check your logs, they now should be more detailed about what caused the ImportError and will point you in the right direction to fix the issue

KeyError with CherryPy WSGIServer serving static files

I'm trying to use CherryPy's WSGI server to serve static files, like in Using Flask with CherryPy to serve static files. Option 2 of the accepted answer there looks exactly like what I'd like to do, but I'm getting a KeyError when I try to use the static directory handler.
What I've tried:
>>>> import cherrypy
>>>> from cherrypy import wsgiserver
>>>> import os
>>>> static_handler = cherrypy.tools.staticdir.handler(section='/', dir=os.path.abspath('server_files')
>>>> d = wsgiserver.WSGIPathInfoDispatcher({'/': static_handler})
>>>> server = wsgiserver.CherryPyWSGIServer(('localhost', 12345), d)
>>>> server.start()
Then, when I try to access the server I'm getting a 500 response and the following error in the console:
KeyError('tools',)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1353, in communicate
req.respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 868, in respond
self.server.gateway(self).respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2267, in respond
response = self.req.server.wsgi_app(self.env, self.start_response)
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2477, in __call__
return app(environ, start_response)
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 175, in handle_func
handled = self.callable(*args, **self._merged_args(kwargs))
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 102, in _merged_args
tm = cherrypy.serving.request.toolmaps[self.namespace]
KeyError: 'tools'
This is displayed twice for each time I try to hit anything that the server should be able to display. When I hooked up a Flask app to the server the Flask app worked as expected, but the static file serving still gave the same error.
What do I need to do to get the staticdir.handler to work?
I've tried various ways of getting this to work and up until today was also hitting the KeyError you have been seeing (among other issues).
I finally managed to get CherryPy to serve static alongside a Django app by adapting the code from this gist (included below).
import os
import cherrypy
from cherrypy import wsgiserver
from my_wsgi_app import wsgi
PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'public'))
class Root(object):
pass
def make_static_config(static_dir_name):
"""
All custom static configurations are set here, since most are common, it
makes sense to generate them just once.
"""
static_path = os.path.join('/', static_dir_name)
path = os.path.join(PATH, static_dir_name)
configuration = {static_path: {
'tools.staticdir.on': True,
'tools.staticdir.dir': path}
}
print configuration
return cherrypy.tree.mount(Root(), '/', config=configuration)
# Assuming your app has media on diferent paths, like 'c', 'i' and 'j'
application = wsgiserver.WSGIPathInfoDispatcher({
'/': wsgi.application,
'/c': make_static_config('c'),
'/j': make_static_config('j'),
'/i': make_static_config('i')})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8070), application,
server_name='www.cherrypy.example')
try:
server.start()
except KeyboardInterrupt:
print "Terminating server..."
server.stop()
Hopefully wrapping a Flask app will be fairly similar.
The key for me was using the cherrypy.tree.mount on a dummy class, rather than trying to use the staticdir.handler directly.
For the curious - I used the code in the gist to customise a version of django-cherrypy's runcpserver management command, although in hindsight it would probably have been easier to create a new command from scratch.
Good luck (and thanks to Alfredo Deza)!

Easy application logging/debugging with nginx, uwsgi, flask?

I'm not looking to turn on the dangerous debugging console, but my application is getting a 500 error and doesn't seem to be writing any output for me to investigate more deeply.
I saw this exchange on the mailing list, which led me to this page on logging errors.
However, I still find this very confusing and have a couple of questions:
(1) In which file should the stuff below go?
ADMINS = ['yourname#example.com']
if not app.debug:
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler('127.0.0.1',
'server-error#example.com',
ADMINS, 'YourApplication Failed')
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
...assuming the "getting bigger" file pattern for larger applications? __init__.py? config.py? run.py?
(2) I am overwhelmed by options there, and can't tell which I should use. Which loggers should I turn on, with what settings, to replicate the local python server debug I get to stdout when I run run.py? I find that default, local output stream very useful, more so than the interactive debugger in the page. Does anyone have a pattern they could share on setting up something replicating this with an nginx deployment, outputting to a log?
(3) Is there anything I need to change, not at the flask level, but in nginx, say in my /etc/nginx/sites-available/appname file, to enable logging?
UPDATE
Specifically, I'm looking for information like I get when python runs locally as to why, say, a package isn't working, or where my syntax error might be, or what variable doesn't exist:
$ python run.py
Traceback (most recent call last):
File "run.py", line 1, in <module>
from myappname import app
File "/home/me/myappname/myappname/__init__.py", line 27, in <module>
file_handler.setLevel(logging.debug)
File "/usr/lib/python2.7/logging/__init__.py", line 710, in setLevel
self.level = _checkLevel(level)
File "/usr/lib/python2.7/logging/__init__.py", line 190, in _checkLevel
raise TypeError("Level not an integer or a valid string: %r" % level)
When I run flask on a server, I never see this. I just get a uWSGI error in the browser, and have no idea which code was problematic. I would just like something like the above to be written to a file.
I notice also that setting the following logging didn't really write much to file, even when I turn the log way up to the DEBUG level:
from logging import FileHandler
file_handler = FileHandler('mylog.log')
file_handler.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)
mylog.log is blank, even when my application errors out.
I'll also add that I've tried to set debug = True in the following ways, in __init__.py:
app = Flask(__name__)
app.debug = True
app.config['DEBUG'] = True
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.config.from_object('config')
app.config.update(DEBUG=True)
app.config['DEBUG'] = True
if __name__ == '__main__':
app.run(debug=True)
While in my config.py file, I have...
debug = True
Debug = True
DEBUG = True
Yet, no debugging happens, and without logging or debugging, this is rather hard to track down. Errors simply terminate the application with the un-useful browser message:
uWSGI Error
Python application not found
Set config['PROPAGATE_EXCEPTIONS'] to True when running app in production and you want tracebacks to be logged into log files. (I haven't tried with SMTP handler, though..)
The part where you create handlers, add to loggers etc. should be in the if __name__ == '__main__' clause, i.e. your main entry point. I assume that would be run.py.
I'm not sure I can answer this - it depends on what you want. I'd advise looking at the logging tutorial to see the various options available.
I don't believe you need to change anything at the nginx level.
Update: You might want to have an exception clause that covers uncaught exceptions, e.g.
if __name__ == '__main__':
try:
app.run(debug=True)
except Exception:
app.logger.exception('Failed')
which should write the traceback of any exception which occurred in app.run() to the log.
I know that this is a VERY old post, but I ran into the issue now, and it took me a bit to find the solution. Flask sends errors to the server. I was running Gunicorn with an upstart script on Ubuntu 14.04 LTS, and the place where I found the error logs was as follows:
/var/log/upstart/myapp.log
http://docs.gunicorn.org/en/stable/deploy.html#upstart
Just in case some other poor soul ends up in this situation.

Categories