Apache Web server using flask, deploying my web app - python

I have a small flask application, and I am trying to host in on my website. It works whenever I run it on my computer, and connect via localhost:5000/ but when I upload to my server, and run the python code, i get multiple errors. When it runs, it only runs on localhost, and can be connected to via the servers console, but when I try to specify that it is to be hosted on all public facing ip's, it says operation not permitted.
here is the terminal output
`/home/public]$ python app.py
Traceback (most recent call last):
File "app.py", line 14, in <module>
app.run(host='0.0.0.0', port=port, debug=True)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 841, in
run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/site-packages/werkzeug/serving.py", line
717, in run_simple
s.bind((hostname, port))
File "/usr/local/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 1] Operation not permitted
`
my app.py
from flask import Flask, render_template, request
import time
app = Flask(__name__)
port=33
#app.route("/")
def index():
x = int(round(time.time() * 1000))
return render_template("index.html", stylevar=x)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=port, debug=True)
if I connect via the domain name, and navigate to /templates, my index.html file will show, but it wont be running the python code.
Would really appreciate any direction on how to get it to be connected to from the browser. I understand that flask is not meant for production environments, but this is just a small personal project. If there are any other environments other than flask this could be accomplished in, I am willing to try something else.

The script does not have the rights for running with a port below of 1024. If you really need to use port 33 you have to run the script as root.

Related

Python Dash server with waitress

I have a dashboard application written in Dash framework.
It also has a few Restful API's written using flask.
I am adding flask app to Dash server, as
import dash
import flask
import dash_bootstrap_components as dbc
flask_server = flask.Flask(__name__)
app = dash.Dash(__name__,server=flask_server, external_stylesheets=[dbc.themes.BOOTSTRAP])
And am running the server as
from dashboard import app
from waitress import serve
if __name__ == "__main__":
app.title = 'Litmus'
app.run_server(debug=False)
# serve(app,host="0.0.0.0",port=8050)
The above code works fine when I am using app.run_server(debug=False) but it throws excetion when I use waitress to run the server.
When I use following lines
#app.run_server(debug=False)
serve(app,host="0.0.0.0",port=8050)
I get following error
ERROR:waitress:Exception while serving /
Traceback (most recent call last):
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\channel.py", line 397, in service
task.service()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 168, in service
self.execute()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 434, in execute
app_iter = self.channel.server.application(environ, start_response)
TypeError: 'Dash' object is not callable
ERROR:waitress:Exception while serving /favicon.ico
Traceback (most recent call last):
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\channel.py", line 397, in service
task.service()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 168, in service
self.execute()
File "C:\Users\litmus\AppData\Roaming\Python\Python38\site-packages\waitress\task.py", line 434, in execute
app_iter = self.channel.server.application(environ, start_response)
TypeError: 'Dash' object is not callable
It's not working because you're passing the Dash app instead of the Flask app to serve.
So instead of this:
serve(app,host="0.0.0.0",port=8050)
pass the Flask app instance like this:
serve(app.server, host="0.0.0.0", port=8050)

An attempt was made to access a socket in a way forbidden by its access permissions (Bottle) (Python)

I've written this code and then ran it via the CMD. However when I ran the code this occurred.
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:80/
Hit Ctrl-C to quit.
Traceback (most recent call last):
File "bottle_01.py", line 7, in <module>
run(host='localhost', port = 80, debug=True)
File "C:\Users\Owner\Desktop\BottleWebApp\bottle.py", line 3137, in run
server.run(app)
File "C:\Users\Owner\Desktop\BottleWebApp\bottle.py", line 2789, in run
srv = make_server(self.host, self.port, app, server_cls, handler_cls)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simple_server.py", line 154, in make_server
server = server_class((host, port), handler_class)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 452, in __init__
self.server_bind()
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simple_server.py", line 50, in server_bind
HTTPServer.server_bind(self)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\http\server.py", line 138, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Now I asked my professor but he's unfamiliar with the issue himself. I searched stackoverflow and I tried to disable my firewall but that didn't seem to help. Any suggestions? Is it an administration issue perhaps? My original code is below.
from bottle import route, run, static_file
#route('/')
def index():
return static_file('webpage_01.html' , root= 'C:/Users/Owner/Desktop/BottleWebApp')
run(host='localhost', port = 80, debug=True)
Does this problem go away when you try port 8000 instead of 80?
You're trying to bind to port 80. I don't know Windows, but on Linux your code would fail because port 80 (like all ports below 1024) is privileged--only root can bind to them. That's why you'll see most tutorials and web framework defaults use a high port number, typically 8000 or 8080.
References:
https://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html
https://en.wikipedia.org/wiki/Registered_port

Server Flask app with cheroot server results to error in HTTPServer.tick after each request

I'm trying to serve a Flask (v1.1.2) wsgi application using cheroot server of CherryPy (v18.6.0) and after each request executed via Postman or browser I'm getting the following exception in my console. I'm running python v3.8.5
Error in HTTPServer.tick
Traceback (most recent call last):
File "C:\myproject\venv\lib\site-packages\cheroot\server.py", line 1795, in serve
self.tick()
File "C:\myproject\venv\lib\site-packages\cheroot\server.py", line 2030, in tick
self.connections.expire()
File "C:\myproject\venv\lib\site-packages\cheroot\connections.py", line 107, in expire
for sock_fd, conn in timed_out_connections:
File "C:\myproject\venv\lib\site-packages\cheroot\connections.py", line 103, in <genexpr>
(sock_fd, conn)
File "C:\python\lib\_collections_abc.py", line 743, in __iter__
for key in self._mapping:
RuntimeError: dictionary changed size during iteration
Code as follows:
from cheroot.wsgi import Server
from flask import Flask
app = Flask(__name__)
#app.route("/", methods=["GET"])
def index():
return "Hello"
if __name__ == "__main__":
server = Server(bind_addr=("0.0.0.0", 3000), wsgi_app=app)
try:
server.start()
finally:
server.stop()
Any idea causing that exception and how we can resolve it?
This is a recent and acknowledged issue with cheroot, take a look to the cheroot GitHub Issue 312.

Deploying CherryPy application using gunicorn

I have a basic application written in CherryPy. It looks somewhat like this:
import cherrypy
class API():
#cherrypy.expose
def index(self):
return "<h3>Its working!<h3>"
if __name__ == '__main__':
cherrypy.config.update({
'server.socket_host': '127.0.0.1',
'server.socket_port': 8082,
})
cherrypy.quickstart(API())
I would like to deploy this application with gunicorn, possibly with multiple workers. gunicorn starts when I run this in terminal
gunicorn -b localhost:8082 -w 4 test_app:API
But everytime I try to access the default method, it gives an internal server error. However, running this standalone using CherryPy works.
Here is the error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/sync.py", line 130, in handle
self.handle_request(listener, req, client, addr)
File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/sync.py", line 171, in handle_request
respiter = self.wsgi(environ, resp.start_response)
TypeError: this constructor takes no arguments
I have a fairly large CherryPy application that I would like to deploy using gunicorn. Is there any to mix CherryPy and gunicorn?

Why wont Web.py let me run a server on port 80?

Im trying to create a website with Web.py but its not letting me open a create a socket on port 80 but it works on every other port.
I have port forwarded and all that so that's not the problem.
python main.py 80
but when I do this I get the error:
http://0.0.0.0:80/
Traceback (most recent call last):
File "main.py", line 43, in <module>
app.run()
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 311, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/usr/local/lib/python2.7/dist-packages/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/usr/local/lib/python2.7/dist-packages/web/httpserver.py", line 148, in runsimple
server.start()
File "/usr/local/lib/python2.7/dist-packages/web/wsgiserver/__init__.py", line 1753, in start
raise socket.error(msg)
socket.error: No socket could be created
my code so far is:
import MySQLdb
import web
import hashlib as h
urls = (
'/', "index", "/register/?", "register", "/login/?", "login", "/thankyou/?", "thankyou"
)
app = web.application(urls, globals())
render = web.template.render("templates/")
db = web.database (dbn="mysql", user="root", pw="461408", db="realmd")
class index():
def GET(self):
return render.index()
class register():
def GET(self):
return render.register()
def POST(self):
i = web.input()
user = h.sha1(i.username).hexdigest()
pw = h.sha1(i.password).hexdigest()
n = db.insert("account", username=user, password=pw)
if __name__ == '__main__':
app.run()
Can someone help please?
You possibly have something else working on port 80. Try the command netstat -ln | grep 80 to check that.
Alternatively, you can try telnet localhost 80, and if the connection is refused then that port should be clear to use.
I successfully start the service by using this command in port 80
sudo python index.py 80
but when I use the shortcut key (control+c) to close the service,there will be an error.
^CTraceback (most recent call last):
File "application.py", line 206, in <module>
app.run()
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/application.py", line 313, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/httpserver.py", line 159, in runsimple
server.stop()
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 1932, in stop
self.requests.stop(self.shutdown_timeout)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 1471, in stop
worker.join(remaining_time)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 680, in join
self.__block.release()
thread.error: release unlocked lock
^C^CException KeyboardInterrupt in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'> ignored
When it happens, I Kill All Python Processes...
killall -9 python
it's can solve the above problems, but not recommended
Visit 127.0.0.1 in a browser. There is likely already a process using port 80, and that port is supposed to be used for http, so that's probably the easiest way to see what's using it.
I ran into the same problem on my RaspberryPi. To fix I just added sudo before the command. Try: sudo python main.py 80
Could it be the fact you're trying to launch web.py as an unprivileged user?
try:
sudo python ./bin/blah.py

Categories

Resources