web connection with python - python

I have this code to create a webapp in my server:
import web
urls = (
'/update', 'Update',
)
app = web.application(urls, globals())
class Update:
print "hola"
if __name__=='__main__':
app.run()
When I try to execute:
python#ubuntu:~$ python prueba.py 8081
hola
http://0.0.0.0:8081/
Traceback (most recent call last):
File "prueba.py", line 21, in <module>
app.run()
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 311, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/usr/local/lib/python2.6/dist-packages/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/usr/local/lib/python2.6/dist-packages/web/httpserver.py", line 148, in runsimple
server.start()
File "/usr/local/lib/python2.6/dist-packages/web/wsgiserver/__init__.py", line 1753, in start
raise socket.error(msg)
socket.error: No socket could be created
Why is it happening?
Thank you in advance

The error message says that it couldn't create a listening socket on the specified port. Check if there is already a server running on port 8081.

Related

Flask And discord Bot ValueError: signal only works in main thread

I am trying to run a discord bot and flask server in one file, I thought it worked but the flask server does nothing so I checked with debug options True, now I get this error:
$ python main.py
Traceback (most recent call last):
File "main.py", line 262, in <module>
run()
File "main.py", line 260, in run
* Serving Flask app 'main'
* Debug mode: on
Tools().discordbot()
File "main.py", line 204, in discordbot
threading.Thread(target=loopy.run_forever).start()
NameError: name 'loopy' is not defined
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:8080
* Running on http://198.54.114.12:8080
Press CTRL+C to quit
Exception in thread Thread-1:
Traceback (most recent call last):
File "/opt/alt/python38/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/opt/alt/python38/lib64/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 213, in __init__
self.RunApi()
File "main.py", line 254, in RunApi
app.run(host="0.0.0.0",port=8080, debug=True)
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/flask/app.py", line 1188, in run
run_simple(t.cast(str, host), port, self, **options)
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/serving.py", line 1090, in run_simple
run_with_reloader(
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/_reloader.py", line 427, in run_with_reloader
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
File "/opt/alt/python38/lib64/python3.8/signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
my contains this to start the discord bot which works fine:
myLoop.start()
threading.Thread(target=loopy.run_forever).start()
loop = asyncio.get_event_loop()
loop.create_task(self.bot.start(self.BotToken))
threading.Thread(target=loop.run_forever).start()
but the flask server does not work, the run command I use for it is this:
class ApiBot:
def __init__(self) -> None:
self.RunApi()
def RunApi(self):
app = Flask(__name__)
#app.route('/auth')
def auth():
code = request.args.get("code")
if (code != None):
if AntiSql(code) == True:
return jsonify({"error":"1004"})
discord = Discordx()
res = discord.ExchangeCode(code)
try:
access_token = res['access_token']
refresh_token = res['refresh_token']
info = discord.GetInfo(access_token)
username = info['username']
avatar = info['avatar']
userid = info['id']
except:
return jsonify({"error":"1005"})
data = {
"access_token": access_token,
"refresh_token": refresh_token,
"username":username,
"avatar":avatar,
"userid":userid,
"ip":request.remote_addr
}
if Memberdb.CheckIfUserIsInDb(data) == False:
Memberdb.AddNewMember(data)
ListToSend.append(data)
return "<script>window.close();</script>"
else:
return jsonify({"error":"1002"})
app.run(host="0.0.0.0",port=8080, debug=True)
def run():
threading.Thread(target=ApiBot).start()
can someone help me? thanks in advance

Getting Errors while using telnetsrv in Python3

I'm creating a telnet server using telnetsrv and green. I'm using python3. Modified the green.py from from telnetsrvlib import TelnetHandlerBase, command to from .telnetsrvlib import TelnetHandlerBase, command and SocketServer to socketserver for python3 compatibility. I'm facing the following errors while connecting to the servers.
[+] Welcome to Telnet server
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run
File "/usr/local/lib/python3.8/dist-packages/gevent/baseserver.py", line 34, in _handle_and_close_when_done
return handle(*args_tuple)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 495, in streamserver_handle
cls(request, address, server)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/green.py", line 14, in __init__
TelnetHandlerBase.__init__(self, request, client_address, server)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 482, in __init__
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
File "/usr/lib/python3.8/socketserver.py", line 748, in __init__
self.setup()
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/green.py", line 18, in setup
TelnetHandlerBase.setup(self)
File "/usr/local/lib/python3.8/dist-packages/telnetsrv/telnetsrvlib.py", line 519, in setup
self.sock = self.request._sock
AttributeError: 'Telnet_handler' object has no attribute 'request'
2022-08-13T15:21:34Z <Greenlet at 0x7f8902e428c0: _handle_and_close_when_done(<bound method TelnetHandlerBase.streamserver_handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket [closed] at 0x7f8902a181c)> failed with AttributeError```
*This is my code*
```#!/usr/bin/python3
import gevent, gevent.server
from telnetsrv.green import TelnetHandler, command
class Telnet_handler(TelnetHandler):
WELCOME = "Welcome to my server."
print(WELCOME)
server = gevent.server.StreamServer(("", 8023),Telnet_handler.streamserver_handle)
try:
print("[+] Welcome to Telnet server")
server.serve_forever()
except KeyboardInterrupt:
print("[-] Connection Failed \n Exiting Telnet Server ")```
[1]: https://i.stack.imgur.com/GuyNX.png

gevent flask in python

I have a code..and a domain name, I
like to use this code to display in my domain name
from flask import Flask
import gevent.wsgi
app=Flask(__name__)
#app.route('/')
def index():
return "hello world"
app_server = gevent.wsgi.WSGIServer(('x.y.z.a'), app)
app_server.serve_forever()
It shows error:
Traceback (most recent call last):
File "p.py", line 10, in <module>
app_server = gevent.wsgi.WSGIServer(('184.171.170.27'), app)
File "/usr/lib/python2.7/dist-packages/gevent/pywsgi.py", line 605, in __init__
StreamServer.__init__(self, listener, backlog=backlog, spawn=spawn, **ssl_args)
File "/usr/lib/python2.7/dist-packages/gevent/server.py", line 48, in __init__
BaseServer.__init__(self, listener, handle=handle, spawn=spawn)
File "/usr/lib/python2.7/dist-packages/gevent/baseserver.py", line 61, in __init__
self.set_listener(listener)
File "/usr/lib/python2.7/dist-packages/gevent/server.py", line 70, in set_listener
BaseServer.set_listener(self, listener)
File "/usr/lib/python2.7/dist-packages/gevent/baseserver.py", line 80, in set_listener
self.family, self.address = parse_address(listener)
File "/usr/lib/python2.7/dist-packages/gevent/baseserver.py", line 323, in parse_address
raise ValueError('Failed to parse address %r: %s' % (address, sys.exc_info()[1]))
ValueError: Failed to parse address '184.171.170.27': invalid literal
for int() with base 10: '184.171.170.27'
What to do.. Thanks for helping
Take a look at gevent's baseserver.py at their github repo.
The address either needs to be a tuple containing the address and the port, or a string with a ":" separating the address from the port. I.e, these would be both valid
app_server = gevent.wsgi.WSGIServer('x.y.z.a:51515', app)
or
app_server = gevent.wsgi.WSGIServer(('x.y.z.a', 51515), app)

How to avoid port error already used in web framework bottle?

In Python3 I have a program to test the web framework bottle:
from bottle import route, run
#route('/')
def index():
return "olá pessoas"
if __name__ == '__main__':
run()
I am running the programs inside a virtualenv, in the command line. But there is this error:
(live-de-python) reinaldo#reinaldo-Inspiron-5567:~/Documentos/Code/live-de-python/repo$ python3 basic_bottle.py
Bottle v0.12.13 server starting up (using WSGIRefServer())...
Listening on http://127.0.0.1:8080/
Hit Ctrl-C to quit.
Traceback (most recent call last):
File "basic_bottle.py", line 11, in <module>
run()
File "/home/reinaldo/Documentos/Code/live-de-python/lib/python3.6/site-packages/bottle.py", line 3127, in run
server.run(app)
File "/home/reinaldo/Documentos/Code/live-de-python/lib/python3.6/site-packages/bottle.py", line 2781, in run
srv = make_server(self.host, self.port, app, server_cls, handler_cls)
File "/usr/lib/python3.6/wsgiref/simple_server.py", line 153, in make_server
server = server_class((host, port), handler_class)
File "/usr/lib/python3.6/socketserver.py", line 453, in __init__
self.server_bind()
File "/usr/lib/python3.6/wsgiref/simple_server.py", line 50, in server_bind
HTTPServer.server_bind(self)
File "/usr/lib/python3.6/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.6/socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
I'm using Ubuntu. Does the error say that port 8080 is already in use? But I have no other program open
Please, does anyone know what it can be?
The port 8080 is already used by an other process. You probably launched the script and forgot to end it. Check with
$ ps -aux | grep basic_bottle
Or simply change the port with run(port=8090).

How to solve the address issue if I restart an external service inside python with flask?

I am using flask to build a python web service, for example, I set the flask port as 8080 like this:
#app.route('/data', methods=['POST'])
def data_construct():
os.system('sh restart.sh')
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=8080)
and the restart.sh is used for restarting an external service, but after I send a HTTP POST request to /data, the restart is successfully completed, but after a while, I get an error:
Traceback (most recent call last):
File "hello.py", line 87, in <module>
app.run(host='0.0.0.0', port=8080)
File "/home/work/.jumbo/lib/python2.7/site-packages/flask/app.py", line 739, in run
run_simple(host, port, self, **options)
File "/home/work/.jumbo/lib/python2.7/site-packages/werkzeug/serving.py", line 613, in run_simple
test_socket.bind((hostname, port))
File "/home/work/.jumbo/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
the 'restart.sh' is like this (storage is a C++-complied program):
killall storage
nohup ./storage &
and I find the external service is starting using the port 8080 which it is not supposed to do (its original port is still in use), how to solve this problem?

Categories