Python Forum
webserver and pythonscript in 1 .py file ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
webserver and pythonscript in 1 .py file ?
#1
hello ,
i'm running this basic webserver and i can send and recieve data from a client via websockets.
this works like a sharm ( html+ javascriptcode is a separated file )

in this code below , i want to send a countervalue to a browser ( connected client )
but if include a function 'counter' in my mainloop ,
then this function blocks the webserverfunctionality , because its includes a while loop and never returns to start the webserver....

how can i run webserver and the infinite counter , which the countervalue wil need to be accessed to send to the client

thx

if this can work as a concept and i can link the 2 scripts then, , i want to make this sytem : https://i.imgur.com/6dRUzMF.png


from aiohttp import web
import socketio
from time import sleep #bestaat op win en raspi


countervalue = 0


## creates a new Async Socket IO Server
sio = socketio.AsyncServer()
## Creates a new Aiohttp Web Application
app = web.Application()
app.router.add_static('/js/', path='static/js')  # parsen browser naar folder
app.router.add_static('/img/', path='static/img')  # parsen browser naar folder
app.router.add_static('/test/', path='./test')  # parsen browser naar folder
# Binds our Socket.IO server to our Web App
## instance
sio.attach(app)

## we can define aiohttp endpoints just as we normally
## would with no change
async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

## If we wanted to create a new websocket endpoint,
## use this decorator, passing in the name of the
## event we wish to listen out for
@sio.on('message')
async def print_message(sid, message):
    ## When we receive a new event of type
    ## 'message' through a socket.io connection
    ## we print the socket ID and the message
    print("Socket ID: " , sid)
    print(message)
    global countervalue
    await sio.emit('message', countervalue, broadcast=True)  # how to send the countervalue to my  browser via this socket???????????????

## We bind our aiohttp endpoint to our app
## router
app.router.add_get('/', index)


def counter():
    global countervalue
    while 1:
        countervalue = countervalue +1
        print(f"teller={countervalue}")
        sleep(2)


def main():
    #counter() #how can i run this function and webserver to ??
    web.run_app(app)




## We kick off our server
if __name__ == '__main__':
    main()
likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  CGI for Basic Python Webserver Mustafa_ba 2 87,437 Mar-05-2017, 06:39 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020