I have a python server to which I can do POST requests. This is the script
from bottle import Bottle, run, template, get, post, request
app = Bottle()
#app.route('/rotation', method='POST')
def set_rotation():
rotation = request.forms.get('rotation')
return rotation
run(app, host='localhost', port=8080)
So in the POST request I send the rotation value and get that in the script. I need the rotation value in another script so I do this in that script
from mybottle import set_rotation
print set_rotation
When I run the first script and then the second script, I get this error
socket.error: [Errno 98] Address already in use
I'm quite new to python so I don't have a clue as to what I'm doing wrong
If you want to be able to import without starting the run function use
if __name__=="__main__"
if __name__=="__main__":
run(app, host='localhost', port=8080)
Each time you import from the file run(app, host='localhost', port=8080) is going to be executed, using if __name__=="__main__" will only start the server when you execute the file itself so you will avoid your socket.error: [Errno 98] which you are getting trying to start the server when it is already running.
You should verify that no other program use the 8080 port, or simply change the port to another value.
I think you run the server twice. The error you get comes from the second server that can't bind on port 8080 because the first is already using it.
Your code, as given, will start a server when imported. This is probably not what you want.
You can avoid this behavior by test the name of your module, which is __main__ only if it's the called script:
if __name__ == '__main__':
run(app, host='localhost', port=8080)
Then, when imported, no server is ran.
Related
I've uploaded some code into a server. The code was working locally but when I upload it to the server it gives me an Internal Server Error. The website is running with wsgi and the code is:
try:
from decksite import main, APP as application
except Exception as e:
from shared import repo
repo.create_issue('Error starting website', exception=e)
if __name__ == '__main__':
print('Running manually. Is something wrong?')
application.run(host='0.0.0.0', debug=False)
So both the try and the except are failing. I want to add a second exception and pass it all to a simple flask application that would output both exceptions to the browser and log them to a file. The problem is that I don't know how to pass the exception to the error_app flask app and that it breaks in the line where I set the logging config. Here is what I've done. I'm only getting NoneType: None instead of the full exception.
import os, sys
sys.path.append("/home/myuser/public_html/flask");
try:
from decksite import main, APP as application
except Exception as error:
#from shared import repo
#repo.create_issue('Error starting decksite', exception=error)
#sys.path.insert(0, os.path.dirname(__file__))
#from error_app import app as application
# This is the code that goes into the error flask application
import logging
import traceback
from flask import Flask, __version__
app = Flask(__name__)
application = app
#app.route("/")
def hello():
return traceback.format_exc()
# The next line gives Internal Server Error
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.exception(error)
return traceback.format_exc()
if __name__ == '__main__':
print('Running manually. Is something wrong?')
application.run(host='0.0.0.0', debug=False)
I don't have sudo in the server and can't ssh to it so unless I'm able to log the errors I'm not going to be able to fix anything.
Edit: I've almost got it as I want:
.htaccess
website.wsgi
error_app.py
website/init.py
website/main.py
Create a custom 500 handler and print out the trackback
import traceback
#app.errorhandler(500)
def internal_server_error(e):
return render_template('500_error.html', traceback=traceback.format_exc())
Have your '500_error.html' template show you the traceback.
You mentioned 500 Internal Server Error is coming. Things are proper in your local but fail on server. Since you don't have ssh access, it might be tough to debug. If you use something like Docker or Kubernetes to build and deploy it can be useful. I can suggest you some ways to debug. The code is not going to try except and failing, the possible reason is the server itself not starting due to missing requirements say some import or it could be anything.
Debug Steps
Create a virtual environment and re-install requirements in it similar to your server. This will help you to identify if there is a missing requirement.
if you are environment is not production and you are testing the application in the server then put debug = True. It will show an error on the front end. This is definitely not a recommended approach. I am suggesting since you don't have ssh access.
If possible create a simple route say /hello and in that just return hello, and check whether it is returning you the right result or not. This will let you know whether your server is starting or not. Even this is not recommendable for production.
You can also check the flask app before request and after request. This might also be useful
Hopefully, 1st step debugging will help you a lot and you might not need to go to step 2 and step 3. I gave you for the worst-case scenario
I am just starting to program on python,
and wrote this code
from bottle import route, run, template
import pymongo
from pymongo import MongoClient
connection = MongoClient('localhost', 27017)
db = connection.tongler
#route('/hello/<name>')
def index(name):
return template("Hello {{name}}", name=name)
run(host='localhost', port=8888)
print db
but it print db object only after terminating 8888 listener, how can I listen for http requests and perform other operations without waiting the http server termination? How is that done?
Once you execute that file, the first command to be executed is the run method call, which starts a process that blocks the rest of the application from being executed until it is closed.
To use the database, you'd have to perform your database operations either as the result of a request, or somewhere before the run method call.
For example, lets say you want to show the records in that database, you might do it like this:
#route('/records/<id>')
def show_records(id=None):
results = db.mycollection.find_one({'id': id})
return template('Record: {{record}}', record=results)
I've developed a tornado app but when more than one user logs in it seems to log the previous user out. I come from an Apache background so I thought tornado would either spawn a thread or fork a process but seems like that is not what is happening.
To mitigate this I've installed nginx and configured it as a reverse proxy to forward incoming requests to an available tornado process. Nginx seems to work fine however when I try to start more than one tornado process using a different port I get the following error:
http_server.listen(options.port)
File "/usr/local/lib/python2.7/dist-packages/tornado/tcpserver.py", line 125, in listen
sockets = bind_sockets(port, address=address)
File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 145, in bind_sockets
sock.bind(sockaddr)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
basically i get this for each process I try to start on a different port.
I've read that I should use supervisor to manage my tornado processes but I'm thinking that is more of a convenience. At the moment I'm wondering if the problem has to do with my actual tornado code or my setup somewhere? My python code looks like this:
from tornado.options import define, options
define("port", default=8000, help="run on given port", type=int)
....
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
my handlers all work fine and I can access the site when I go to localhost:8000 just need a pair of fresh eyes please. ;)
Well I solved the problem. I had .sh file that tried to start multiple processes with:
python initpumpkin.py --port=8000&
python initpumpkin.py --port=8001&
python initpumpkin.py --port=8002&
python initpumpkin.py --port=8003&
unfortunately I didn't tell tornado to parse the command line options so I would always get that address always in use error since port '8000' was defined as my default port, so it would attempt to listen on that port each time. In order to mitigate this make sure to declare tornado.options.parse_command_line() after main:
if __name__ == "__main__":
tornado.options.parse_command_line()
then run from the CLI with whatever arguments.
Have you tried starting your server in this manner:
server = tornado.httpserver.HTTPServer(app)
server.bind(port, "0.0.0.0")
server.start(0)
IOLoop.current().start()
server.start takes a parameter for number of processes where 0 tells Tornado to use one process per CPU on the machine
I want to work with Tor through Stem module.The following is my code to get connected with Tor:
import sys
from stem.connection import connect
if __name__ == '__main__':
controller = connect()
if not controller:
sys.exit(1) # unable to get a connection
print 'Tor is running version %s' % controller.get_version()
controller.close()
However, i get following error when running the code:Unable to connect to tor. Are you sure it's running?
I turned on Tor and tested the code again and nothing happened. The problem is this line:
if __name__ == '__main__':
controller = connect()
Even if I enter the connect() method to Python interpreter I get the error. What is the error and how can I fix it?
I am attempting to display an image on localhost. As a first step, I have created a sever script in python
#!/usr/bin/env python
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = ["/"]
httpd = server(server_address, handler)
httpd.serve_forever()
The image is placed within the same directory where this script is executing.
Subsequently http://localhost:8000/test.jpg is typed in the browser.
The browser fails to render the image with an error:
The image "http://localhost:8000/test.jpg" cannot be displayed because it contains errors.
The server script throws an error like
File "/usr/lib/python2.7/CGIHTTPServer.py", line 253, in run_cgi
os.execve(scriptfile, args, env)
OSError: [Errno 8] Exec format error
I have tried displaying text and the server works fine with lot of examples. Except that it fails to load images. Where am I going wrong?
The problem was solved. I moved the test.jpg into a sub-directory within the
server directory.
Your code is attempting to execute the test.jpg as a cgi script. If you remove the CGIHttpRequestHandler and instead use SimpleHTTPServer.SimpleHTTPRequestHandler you will get your image back. If you need both, then you need to put the image somewhere else.
CGI is used to execute server-side scripts, not to serve static content. It will therefore attempt to execute files that are being served (in this case, attempting to execute an image): os.execve(scriptfile, args, env).
Execution is equivalent to running the file at your shell.
Use SimpleHTTPServer for static content, such as images.
I believe the error is because you have no html page setup.
Your python script although is running a server on your localhost, but you need html/css pages
to actually display pictures and words.