profile
viewpoint

miguelgrinberg/flask-celery-example 758

This repository contains the example code for my blog article Using Celery with Flask.

miguelgrinberg/flack 404

Companion code to my PyCon 2016 "Flask at Scale" tutorial session.

miguelgrinberg/api-pycon2015 149

Code for my PyCon talk "Is Your REST API RESTful?"

miguelgrinberg/api-pycon2014 124

Code for my PyCon talk "Writing RESTful Web Services with Flask"

miguelgrinberg/flask-examples 63

Code for my "Python Web Development with Flask" presentation.

miguelgrinberg/flask 43

A microframework based on Werkzeug, Jinja2 and good intentions

miguelgrinberg/climax 29

A lightweight argparse wrapper inspired by click.

miguelgrinberg/anaglyph.py 25

3D Anaglyph image generator

miguelgrinberg/asyncio-testing 25

Unit testing asyncio code

miguelgrinberg/easy-etcd 17

Start an etcd cluster with ease!

issue commentmiguelgrinberg/climax

Support custom argparse in regular command like subcommand

Release 0.4.0 is out with this change.

mtyurt

comment created time in 16 hours

created tagmiguelgrinberg/climax

tagv0.4.0

A lightweight argparse wrapper inspired by click.

created time in 16 hours

push eventmiguelgrinberg/climax

Miguel Grinberg

commit sha 998fc09c6ea7294846e5e7c4d8ce932eaabdf213

Release 0.4.0

view details

push time in 16 hours

push eventmiguelgrinberg/climax

Miguel Grinberg

commit sha bc0e3bb6d5b93c735091c30a70947a0c823b61c9

Release 0.3.2

view details

Miguel Grinberg

commit sha 8fa9f4fb1f992a4f498d3a291aad2318bf17ef42

fixed setup.py long description

view details

push time in 16 hours

created tagmiguelgrinberg/climax

tagv0.3.2

A lightweight argparse wrapper inspired by click.

created time in 16 hours

issue commentmiguelgrinberg/microdot

send_file fails with larger files

Give the microdot.py version in the master branch a try. I have changed it to send file downloads in blocks of 1024 bytes now.

xorbit

comment created time in a day

push eventmiguelgrinberg/microdot

Miguel Grinberg

commit sha 3e29af57753dbb7961ff98719a4fc4f71c0b4e3e

Support large downloads in send_file (fixes #3)

view details

Miguel Grinberg

commit sha dfbe2edd797153fc9be40bc1928d93bdee7e7be5

Update python versions to build

view details

push time in a day

issue closedmiguelgrinberg/microdot

send_file fails with larger files

send_file is great but it seems to have an issue with larger files.

When trying to send an 18k JPG, I get this:

Unhandled exception in thread started by <closure>
Traceback (most recent call last):
  File "/lib/microdot.py", line 24, in run
  File "/lib/microdot.py", line 390, in dispatch_request
  File "/lib/microdot.py", line 210, in write
OSError: [Errno 104] ECONNRESET

Looking at the code, I think a likely problem is that it reads the whole file into memory before it sends it. Is there a way to do this differently, more like a stream architecture, so it doesn't need so much memory?

closed time in a day

xorbit

pull request commentmiguelgrinberg/climax

Add external argparse instance support to main command

Looks good, thank you so much!

mtyurt

comment created time in a day

push eventmiguelgrinberg/climax

M. Tarık Yurt

commit sha 2a9ba139b181e1b3bf4e222787f64052bf33f369

Add external argparse instance support While subcommands have the support of an external `Argparse` instance, main commands do not have this flexibility. This commit aims to implement that behavior. I tried to modify minimum amount of code parts. I did not use `_CopiedArgumentParser` because it seemed to be only usable in subcommand structure, since no other code part uses `_parser_class`. I'm not sure if it is a good idea, but with the initial version, the wrapper supports both an external instance and annotation argument definitions, as such can be seen in the tests. This commit fixes #5.

view details

Miguel Grinberg

commit sha f8230900f5a5c06a33f882df7145e5b5a3644c4f

Merge pull request #6 from mtyurt/external-argparse-for-main Add external argparse instance support to main command

view details

push time in a day

PR merged miguelgrinberg/climax

Add external argparse instance support to main command

While subcommands have the support of an external Argparse instance, main commands do not have this flexibility. This commit aims to implement that behavior.

I tried to modify minimum amount of code parts. I did not use _CopiedArgumentParser because it seemed to be only usable in subcommand structure, since no other code part uses _parser_class.

I'm not sure if it is a good idea, but with the initial version, the wrapper supports both an external instance and annotation argument definitions, as such can be seen in the tests.

This commit fixes #5.

+42 -2

0 comment

3 changed files

mtyurt

pr closed time in a day

issue closedmiguelgrinberg/climax

Support custom argparse in regular command like subcommand

Hello,

The reason I'm asking for this feature is to add mutually exclusive argument group support to the main command definition. Current subcommand example provides this feature, but to the subcommand, not to the main command. This feature would open more doors and possibilities to the climax's usage.

I may give implementing a try if you approve this feature request.

Thanks for the library, it's a great wrapper!

closed time in a day

mtyurt

issue closedmiguelgrinberg/microdot

upip install fails

Hi Miguel,

Even though Microdot seems to be in the Pypi repo, I cannot install it. I'm using "MicroPython v1.12 on 2019-12-20; ESP32 module with ESP32"

>>> upip.install('microdot')
Installing to: /lib/
Warning: micropython.org SSL certificate is not validated
Error installing 'microdot': , packages may be partially installed
>>> import microdot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: no module named 'microdot'
>>> 

Any ideas?

closed time in a day

xorbit

issue commentmiguelgrinberg/microdot

send_file fails with larger files

Yes, large files would not work with the current implementation.

The Response.write() method assumes self.body contains the bytes, all in memory. We can accept a file-like object as body, and then the write can be done in small chunks. Would that work?

xorbit

comment created time in a day

issue commentmiguelgrinberg/microdot

upip install fails

Picoweb has been broken for a very long time. That is one of the reasons I created microdot! Thanks.

xorbit

comment created time in a day

push eventmiguelgrinberg/climax

Miguel Grinberg

commit sha 1efe841fcc976e994f62c9212052cfc85b8fa984

update python versions in build

view details

push time in a day

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

I think you are making this more complicated that it needs to be. As I said, the Socket.IO server logs a lot of useful information. By default this log goes to stdout. Make it go to a file for example, or an email if you don't have access to the file system. The logging package in Python is powerful, you can do a lot of things with it.

Aarlangdi

comment created time in a day

issue commentmiguelgrinberg/microdot

upip install fails

Can you try again? The problem was caused by having wheel package along with the source distribution uploaded to PyPI. That confuses upip. I have now removed all the wheel packages.

On the Mac MicroPython I can get it installed just fine. On the ESP8266 it fails with a different error, which could be memory. I don't have an ESP32 at hand right now, so can you please test it on your side and report?

xorbit

comment created time in a day

issue commentmiguelgrinberg/microdot

upip install fails

Unfortunately upip isn't giving an error message, note the "," between the colon and the word "packages". It's supposed to show an error message there and it isn't, so I do not know. I can confirm that I get the same error on the ESP8266, and also on the MacOS release.

The fact it happens on several platforms including a desktop one suggests it is not memory related. I'll have to investigate this more to know what's going on.

xorbit

comment created time in a day

issue commentmiguelgrinberg/climax

Support custom argparse in regular command like subcommand

Yeah, that sounds good. Happy to accept this as a PR!

mtyurt

comment created time in a day

issue commentmiguelgrinberg/climax

Support custom argparse in regular command like subcommand

When you say "custom argparse" do you mean attaching an argparse instance that you built outside of this package?

mtyurt

comment created time in a day

issue commentmiguelgrinberg/flasky-with-celery

is a new flask app created when running `celery worker -A celery_worker.celery`?

Yes, each process has its own Flask app instance. The Celery workers do not run a web server through, the app in those processes is there to support any extensions that require an app context to access app resources such as configuration.

royling

comment created time in 2 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

I have zero knowledge of cpanel, so no, I cannot help much with that.

Aarlangdi

comment created time in 2 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

Well, I don't know how you configure your app logs. This is the application, so you must know where you app logs go to. Maybe to standard output, which is the default. Clearly you are not looking in the correct place. I do not use cpanel, so I cannot assist you with specifics to that platform.

Aarlangdi

comment created time in 2 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

I do not know what logs you are giving me. I asked for Socket.IO logs. You had the instructions to get these logs in the issue template. I copied them again for you in this thread. Here they are a third time:

Logs Please provide relevant logs from the server and the client. On the server, add the logger=True and engineio_logger=True arguments to your SockertIO() object to get logs dumped on your terminal. The same arguments can be used on the python-socketio's client. If you are using the JavaScript client, see here for how to enable logs.

Aarlangdi

comment created time in 2 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

I need to see your logs, please.

Aarlangdi

comment created time in 2 days

issue commentmiguelgrinberg/python-socketio

Horizontal scaling and publishing to a SID

Your code is incomplete, I think:

  • Custom rooms don't seem to be implemented. You assume there is a channel for each room, but only sid rooms are initialized so that the server listens on them.
  • Broadcasts to everyone do not appear to be supported either.
  • I mentioned this before, the sid rooms currently do not prevent changes. They should be locked to make this feature robust.

As much optimized Redis is, there's got to be a cost to having potentially large numbers of channels. As an implementation it seems

dfee

comment created time in 2 days

issue commentmiguelgrinberg/python-socketio

Horizontal scaling and publishing to a SID

Knowing which server each player is connected to is precisely what using separate pubsub channels per sid implicitly accomplishes.

So if each server hosts 5000 clients you want the server to listen on 5000 different channels, while each of the other servers also listen on their own set of 5000ish clients? Does sound too good to me, but regardless, I think you should be able to implement a pubsub client manager subclass that does this. The tricky part would be enforcing that these sid-based rooms are locked.

dfee

comment created time in 2 days

issue commentmiguelgrinberg/python-socketio

Horizontal scaling and publishing to a SID

First of all, you are starting from the assumption that you know on which server each player is. This is not typical, in most cases clients are randomly assigned a server. If you know on which server your client is, then you can just do the emit on that server using the option to skip the message queue.

For the "normal" case where you have servers behind a load balancer, you really don't know where each client is, as this is determined by the load balancer. Sending a message to a single client (or to a room) requires every server checking if it knows the recipient. The case that I said above to the OP that could be optimized is when there is an emit to a user room, and the server in which the emit is issued is the one where that client is hosted. In that case going out to the message queue is unnecessary. But for this to be possible user rooms need to be treated specially, they need to be marked as such, and you should not be able to add/remove participants from them.

dfee

comment created time in 2 days

issue commentmiguelgrinberg/Flask-SocketIO

How i save and show existing progress status using flask socketio if browser is closed(session)

@Set4now all cloud based solutions require that you authenticate with them before you can see your dashboard. They associate the state of your account with your identity. Authentication does not need to be based in Flask, as long as you know who the user is you can store the current state in your database and recall it when the user reconnects.

Set4now

comment created time in 2 days

issue commentmiguelgrinberg/python-socketio

Horizontal scaling and publishing to a SID

Still have questions.

If these two groups of clients (bots & humans) never interact with each other, why don't you use two separate servers, or maybe use a single server, but set the redis channel to socketio-bots in the bot servers and socketio-humans in the human servers?

dfee

comment created time in 3 days

issue commentmiguelgrinberg/python-socketio

Horizontal scaling and publishing to a SID

Maybe I do not understand fully your situation, but why don't you pass a different channel name when you create your redis client manager? https://github.com/miguelgrinberg/python-socketio/blob/master/socketio/redis_manager.py#L31-L32.

dfee

comment created time in 3 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

Instead of selecting the line that you think is significant from the server logs, please show me the entire content. You are missing important content there, I think.

Aarlangdi

comment created time in 3 days

issue commentmiguelgrinberg/Flask-SocketIO

Packet loss? Emitting problem (getting slow over time)

Did you notice the bug template when you wrote your issue? It is important that you provide the information requested. Without logs I cannot do much analysis of your problem.

BlasterL

comment created time in 4 days

push eventmiguelgrinberg/python-engineio

Miguel Grinberg

commit sha 658e811002c3c4356b1be9b28380c3018371c84c

stop building python 2.7

view details

push time in 5 days

push eventmiguelgrinberg/python-socketio

Miguel Grinberg

commit sha 2a54f6c020a7d93d10ecbd1a64337bd6fa068d30

Remove unneeded data argument #nolog

view details

Miguel Grinberg

commit sha dc89963e328920a3756cefb508213c310ffa730c

Initialize the client's SIGINT signal handler if a client is created (Fixes #424)

view details

Miguel Grinberg

commit sha a0abd7af6ee0459b0cd482b50e3d5d8ae71bec95

stop building python 2.7

view details

push time in 5 days

issue closedmiguelgrinberg/python-socketio

"ValueError: signal only works in main thread" when using the server

When using the server together with aiohttp, I'm getting the error

ValueError: signal only works in main thread

from https://github.com/miguelgrinberg/python-socketio/blob/master/socketio/client.py#L28. Can we have the same fix as in https://github.com/miguelgrinberg/python-engineio/commit/6534d324f3dce2e1e4927932660d5e5e8bcab202 also for socketio? That would help a lot! At the moment I'm doing this ugly workaround:

        import signal
        origsignal = signal.signal
        signal.signal = lambda x, y: None
        from socketio.asyncio_server import AsyncServer
        signal.signal = origsignal

closed time in 5 days

pcmoritz

issue commentmiguelgrinberg/python-engineio

Cannot create Client object when using threading

@rogerio-alves I have changed it so that the signal handler is only configured when the client lives in the main thread.

The downside is that Ctrl-C will not provide clean up when you have your client in another thread.

Can you give the master branch of this repo a try, and confirm that you do not get the error anymore?

rogerio-alves

comment created time in 5 days

push eventmiguelgrinberg/python-engineio

Miguel Grinberg

commit sha e1ed079a8dafe2b9ca596fa2fc2885a91d1b486d

Only add signal handler when client is created in main thread (Fixes #163)

view details

push time in 5 days

issue closedmiguelgrinberg/python-engineio

Cannot create Client object when using threading

Hi!

I'm using socketio in a multithreaded app using the threading module. When updating from python-engineio 3.11.1 to python-engineio 3.11.2, there is an apparent issue with initializing the SIGINT signal handler when the Client object is created. This happens only if it is made outside the main thread, as suggested by the official python docs. The exception launched is:

ValueError: signal only works in main thread

I've seen that the initialization was made only if the file was running as __main__ in previous versions and was changed due to issue #147 . Is it considered a bad practice to use socketio in a multithreaded app? Or is there any reason to only use it in the main thread?

The full traceback is as follows:

Traceback (most recent call last):
  File "/home/rogerio/git/proj/threads/communication.py", line 59, in event_client_thread
    sio = socketio.Client()
  File "/home/rogerio/.local/lib/python3.6/site-packages/socketio/client.py", line 97, in __init__
    self.eio = self._engineio_client_class()(**engineio_options)
  File "/home/rogerio/.local/lib/python3.6/site-packages/engineio/client.py", line 82, in __init__
    signal_handler)
  File "/usr/lib/python3.6/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

closed time in 5 days

rogerio-alves

issue commentmiguelgrinberg/Flask-SocketIO

Sending image to client without receiving the image from client.

@iszzul sorry, I don't really know how to help you with your webcam issue.

iszzul

comment created time in 5 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

As I said, when you wrote your issue here you had the information on how to generate additional logs. Here is that info again for your convenience:

Logs Please provide relevant logs from the server and the client. On the server, add the logger=True and engineio_logger=True arguments to your SockertIO() object to get logs dumped on your terminal. The same arguments can be used on the python-socketio's client. If you are using the JavaScript client, see here for how to enable logs.

Aarlangdi

comment created time in 5 days

issue commentmiguelgrinberg/flask-video-streaming

page is not loading properly with multiple stream when getting the datas from user

@srp6996 sorry, not familiar with your camera. Probably your new camera uses a different format.

srp6996

comment created time in 5 days

pull request commentmiguelgrinberg/Flask-Moment

Add toTime and toNow to display functions

Thanks!

mrf345

comment created time in 5 days

push eventmiguelgrinberg/Flask-Moment

Mohamed Feddad

commit sha 13ba7ee3b0ab8d0e7aa774781ef3b3ec33cad9ce

Add toTime and toNow to display functions (#57) * Add toTime and toNow to display functions * Add toNow and toTime to example app

view details

push time in 5 days

PR merged miguelgrinberg/Flask-Moment

Reviewers
Add toTime and toNow to display functions enhancement

Problem:

MomentJS >= 2.10.3 supports .to and .toNow functions which give the ability to display an opposite interval to .from and .fromNow. MomentJS Docs

Solution:

  • Add toTime and toNow display functions.
  • Add test coverage.
  • Update README.
  • Add functions to the example app.

Thanks so much for the awesome extension 🚀

+53 -2

2 comments

5 changed files

mrf345

pr closed time in 5 days

push eventmiguelgrinberg/Flask-SocketIO

Miguel Grinberg

commit sha c41e25643bc9f64147f1a8c82e0a8176a303ea46

update travis build versions #nolog

view details

push time in 5 days

issue closedmiguelgrinberg/python-socketio

Checking data is None in {AsyncServer,Server}._emit_internal()

In AsyncClient, the case data is not None is checked so the server will receive an empty list as data.

https://github.com/miguelgrinberg/python-socketio/blob/aa2882cb3e2f3cda3a9d8c94b1c5db1bd0dbbf99/socketio/asyncio_client.py#L167

However, in AsyncServer, the case data is not None is not checked so [None] is passed to client instead of an empty list []. https://github.com/miguelgrinberg/python-socketio/blob/aa2882cb3e2f3cda3a9d8c94b1c5db1bd0dbbf99/socketio/asyncio_server.py#L357

So the behavior is not symmetric between server and client.

There is a similar situation in the Server class as well.

I think this is a bug.

closed time in 5 days

tsangwpx

push eventmiguelgrinberg/python-socketio

Miguel Grinberg

commit sha f1a2e545c8407bd9523e540ab1f5afbfa970b69d

missing unit tests #nolog

view details

push time in 5 days

push eventmiguelgrinberg/python-socketio

Aaron

commit sha e2242ce40e65c682e031d245db50fdd7956c3b2d

Fix Server and AsyncServer when emitting no data (#420)

view details

push time in 5 days

pull request commentmiguelgrinberg/python-engineio

Do not hang in polling while websocket upgrade is ongoing

Unfortunately I haven't been able to reproduce this problem, so I cannot test this solution. Do you think you could use the self.upgrading and self.upgraded booleans instead of adding the new self.poll_ended? You could equate self.poll_ended == False to not self.upgraded or self.upgrading I think, and self.poll_ended == True would be the same as self.upgraded == True.

salimaboubacar

comment created time in 5 days

push eventmiguelgrinberg/python-engineio

Miguel Grinberg

commit sha 5260f5c4d8e6091fb913be9b688d61e36c11fb26

More accurate logging documentation (Fixes #158)

view details

push time in 5 days

issue closedmiguelgrinberg/python-engineio

logger can't be disabled

The following code treats logger=False as logger=True.

https://github.com/miguelgrinberg/python-engineio/blob/a67b3d76d80e665ec071292dc4aadffb50be6d3f/engineio/client.py#L104-L114

The docstring says otherwise:

https://github.com/miguelgrinberg/python-engineio/blob/a67b3d76d80e665ec071292dc4aadffb50be6d3f/engineio/client.py#L58-L60

closed time in 5 days

buckle2000

push eventmiguelgrinberg/python-socketio

Miguel Grinberg

commit sha d745477abf606f56f566f9d5b1b7bf9ffdb4fbc6

More accurate logging documentation

view details

push time in 5 days

push eventmiguelgrinberg/Flask-SocketIO

Miguel Grinberg

commit sha 255d3d6b41b4f22736d2798a8f70264334eb3173

More accurate logging documentation

view details

push time in 5 days

issue closedmiguelgrinberg/python-engineio

Websocket/Requests support for ignoring invalid SSL certs (and passing arbitrary connect params)

Hi,

Request: I'd like to request a way to pass arbitrary connection options to the polling and websocket connect calls. This would probably lend itself to a change in the python-socketio library as well to be able to pass these down to EngineIO, but even just support in EngineIO would be good.

Specific Issue: We sometimes need to connect through SSL terminated proxies inside our network that don't have valid SSL certs, and would like support for passing SSL cert ignore options to the request and websocket clients' connection calls.

verify=False would be useful here: https://github.com/miguelgrinberg/python-engineio/blob/d6a33d22cfd3ebe8b4d78cd5c27607de837d16e9/engineio/client.py#L433

I'd like to be able to pass the sslopt keyword arg to the websocket connect, but it would be good to support any other options that the requests and websocket connection methods take.

sslopt={"cert_reqs": ssl.CERT_NONE} would be useful here: https://github.com/miguelgrinberg/python-engineio/blob/d6a33d22cfd3ebe8b4d78cd5c27607de837d16e9/engineio/client.py#L332-L333

More info on the Websocket SSL ignore: https://github.com/websocket-client/websocket-client#how-to-disable-ssl-cert-verification

Here's what I'm doing now as a workaround:

"""
Customized SocketIO and EngineIO classes so we can pass an "ignore valid SSL cert" to the websocket connection.

TODO: Remove this if the EngineIO library adds params for passing this.
"""
import ssl

import engineio
import socketio
import requests
import websocket

class MyEngineIoClient(engineio.Client):
    def _send_request(
            self, method, url, headers=None, body=None):  # pragma: no cover
        if self.http is None:
            self.http = requests.Session()
        try:
            return self.http.request(method, url, headers=headers, data=body, verify=False)
        except requests.exceptions.ConnectionError:
            pass

    def _connect_websocket(self, url, headers, engineio_path):
        """Establish or upgrade to a WebSocket connection with the server."""
        if websocket is None:  # pragma: no cover
            # not installed
            self.logger.warning('websocket-client package not installed, only '
                                'polling transport is available')
            return False
        websocket_url = self._get_engineio_url(url, engineio_path, 'websocket')
        if self.sid:
            self.logger.info(
                'Attempting WebSocket upgrade to ' + websocket_url)
            upgrade = True
            websocket_url += '&sid=' + self.sid
        else:
            upgrade = False
            self.base_url = websocket_url
            self.logger.info(
                'Attempting WebSocket connection to ' + websocket_url)
        try:
            ws = websocket.create_connection(
                websocket_url + self._get_url_timestamp(),
                header=headers,
                sslopt={"cert_reqs": ssl.CERT_NONE}
            )
        except ConnectionError:
            if upgrade:
                self.logger.warning(
                    'WebSocket upgrade failed: connection error')
                return False
            else:
                raise engineio.exceptions.ConnectionError('Connection error')
        if upgrade:
            p = engineio.packet.Packet(engineio.packet.PING, data='probe').encode()
            try:
                ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            try:
                p = ws.recv()
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected recv exception: %s',
                    str(e))
                return False
            pkt = engineio.packet.Packet(encoded_packet=p)
            if pkt.packet_type != engineio.packet.PONG or pkt.data != 'probe':
                self.logger.warning(
                    'WebSocket upgrade failed: no PONG packet')
                return False
            p = engineio.packet.Packet(engineio.packet.UPGRADE).encode()
            try:
                ws.send(p)
            except Exception as e:  # pragma: no cover
                self.logger.warning(
                    'WebSocket upgrade failed: unexpected send exception: %s',
                    str(e))
                return False
            self.current_transport = 'websocket'
            self.logger.info('WebSocket upgrade was successful')
        else:
            try:
                p = ws.recv()
            except Exception as e:  # pragma: no cover
                raise engineio.exceptions.ConnectionError(
                    'Unexpected recv exception: ' + str(e))
            open_packet = engineio.packet.Packet(encoded_packet=p)
            if open_packet.packet_type != engineio.packet.OPEN:
                raise engineio.exceptions.ConnectionError('no OPEN packet')
            self.logger.info(
                'WebSocket connection accepted with ' + str(open_packet.data))
            self.sid = open_packet.data['sid']
            self.upgrades = open_packet.data['upgrades']
            self.ping_interval = open_packet.data['pingInterval'] / 1000.0
            self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0
            self.current_transport = 'websocket'

            self.state = 'connected'
            engineio.client.connected_clients.append(self)
            self._trigger_event('connect', run_async=False)
        self.ws = ws

        # start background tasks associated with this client
        self.ping_loop_task = self.start_background_task(self._ping_loop)
        self.write_loop_task = self.start_background_task(self._write_loop)
        self.read_loop_task = self.start_background_task(
            self._read_loop_websocket)
        return True


class MySocketIoClient(socketio.Client):
    def _engineio_client_class(self):
        return MyEngineIoClient

closed time in 5 days

harmon

issue commentmiguelgrinberg/python-socketio

Asyncio client hangs

@hamidb80 I think you need to review more carefully the rules for writing an asyncio application. Unfortunately your application is not trivial to run, but looking at it I see that you are using threads and the time.sleep() function, so my guess is that these two are blocking the asyncio loop somehow. Why are you using threads on an asyncio application? In general it is not a good idea because it is hard to mix threads with an asyncio loop. Most people run non-asyncio code in a thread or process executor pool to avoid problems.

hamidb80

comment created time in 5 days

pull request commentmiguelgrinberg/Flask-Moment

Add toTime and toNow to display functions

Could you add the two new functions to the example app? Other than that this looks good, thank you so much!

mrf345

comment created time in 5 days

issue commentmiguelgrinberg/Flask-SocketIO

Sending image to client without receiving the image from client.

You can send images in binary form, just include a bytes string, ie data['data'] = image_read. No need to convert to a base64 string, binary blobs are supported. If you get an error, please show the error, without that I cannot tell you what's wrong.

iszzul

comment created time in 5 days

issue commentmiguelgrinberg/python-socketio

'int' object has no attribute 'encode'

first name dot last name at gmail

higrw123

comment created time in 5 days

issue commentmiguelgrinberg/Flask-SocketIO

Where have I to store sqlalchemy object

You can store data in the session without changing the manage_session setting. Note that Flask expects anything you write in the user session to be serializable to JSON, so you may run into trouble writing a SQLAlchemy model.

ivan-fr

comment created time in 5 days

issue commentmiguelgrinberg/Flask-SocketIO

Invalid session error in cpanel socket app / 400 error code in browser

Did you notice that the bug template includes information on how to capture mode detailed logs? Without that it is hard for me to figure out what went wrong.

Aarlangdi

comment created time in 5 days

issue commentmiguelgrinberg/python-socketio

Aiohttp Server: "TypeError: handle_connect() takes 0 positional arguments but 2 were given"

So you have a function called handle_connect(), yes? This function should take two arguments, sid and environ. See the docs.

secretlyvogon

comment created time in 5 days

issue commentmiguelgrinberg/python-socketio

Asyncio client sucks

Bit of advice. If you expect help, it's probably not a good idea to claim that the project you are trying to get help on "sucks".

Please provide example code I can use to verify your delay. Or instructions to reproduce this problem using any of the examples in this repository. How would you feel if I were to claim that the way you report problems also sucks? Please try to be civil. The person on the other side is a human, not a machine.

hamidb80

comment created time in 5 days

issue commentmiguelgrinberg/python-socketio

Geting answer from JS server on Python client

To wait for events call sio.wait(). Also move the sio.connect() call to the bottom, after you define your handlers.

OscarSoto6

comment created time in 5 days

issue commentmiguelgrinberg/python-engineio

Cannot create Client object when using threading

I'll look into it. The change that I've made in 3.11.2 was to address a similar error, it seems I did not cover all possibilities with my fix.

rogerio-alves

comment created time in 6 days

issue commentmiguelgrinberg/python-socketio

Disable reconnecion in client

The docs are your friend. All the reconnection options are documented here: https://python-socketio.readthedocs.io/en/latest/api.html#socketio.Client.

hamidb80

comment created time in 6 days

issue commentmiguelgrinberg/python-socketio

'int' object has no attribute 'encode'

This is a duplicate of https://github.com/miguelgrinberg/python-socketio/issues/417. Do you have a client and server I can use to reproduce this problem?

higrw123

comment created time in 6 days

issue commentmiguelgrinberg/python-socketio

Aiohttp Server: "TypeError: handle_connect() takes 0 positional arguments but 2 were given"

Do you have the stacktrace for the server error?

secretlyvogon

comment created time in 6 days

issue commentmiguelgrinberg/python-socketio

socket over flask and https

This package does not really care about https, the encryption/decryption is all handled by your web server. That's where you should be looking for the problem, I think.

mmayor

comment created time in 7 days

issue commentmiguelgrinberg/python-socketio

socket over flask and https

I'm sorry but I don't understand what you are asking. Best variant of what?

mmayor

comment created time in 7 days

pull request commentmiguelgrinberg/python-socketio

fix the bug that socketio can't emit event disconnnect when call disconnect()

Did you look at the history in git regarding that line you are commenting out? It was put there specifically to address an issue, you can't just comment it out. Also if you can explain more clearly what case you are trying to address I would appreciate it.

higrw123

comment created time in 7 days

Pull request review commentmiguelgrinberg/python-engineio

SSL certificate trusting by adding a 'cert' parameter to client connections

 def _reset(self):             headers = headers.copy()             headers['Cookie'] = cookies +        sslopt = {'certfile': cert}         try:             ws = await websockets.connect(                 websocket_url + self._get_url_timestamp(),-                extra_headers=headers)+                extra_headers=headers, sslopt=sslopt)

Are you sure this is right? My understanding was that this websocket client takes an SSLContext object in the ssl argument, I don't believe sslopt is a valid argument.

ConradBailey

comment created time in 7 days

Pull request review commentmiguelgrinberg/python-engineio

SSL certificate trusting by adding a 'cert' parameter to client connections

 def _reset(self):      async def _send_request(             self, method, url, headers=None, body=None,-            timeout=None):  # pragma: no cover+            timeout=None, cert=None):  # pragma: no cover         if self.http is None or self.http.closed:             self.http = aiohttp.ClientSession()         http_method = getattr(self.http, method.lower())+        ssl_context = ssl.create_default_context(cafile=cert)

It seems doing this every time a request is sent is not necessary, right? The context can be saved to a this.ssl_context member variable and reused.

ConradBailey

comment created time in 7 days

issue commentmiguelgrinberg/Flask-SocketIO

nginx + uwsgi + greenlet bad file descriptor

@0x78f1935 I can't offer any advice on this problem, but just wanted to mention that you should pin your dependencies. It's crazy to deploy with latest packages every time. It sort of invalidates any testing that you do on your own, since each deployment brings new code into the mix.

dank69

comment created time in 8 days

issue commentmiguelgrinberg/Flask-SocketIO

Ambiguities with the use of socketio.run(app) with uWSGI.

1: why is the callable that uwsgi uses the callable exposed by vanilla flask (in my case app), and not the wrapper socketio created through socketio = SocketIO(app)

The app variable holds a WSGI callable, while socketio is just a Flask extension that enhances the Flask app. Like most/all extensions, it does not replace your app, just adds new tricks to it.

2: in your documentation socketio.run(app) is only run when the script is run directly. Does socketio.run(app) spin up a web server through flask, and that's why we don't want to use it when uWSGI is hooking into a flask callable?

The socketio.run(app) method of running the server is implemented for the gevent, eventlet and Flask web servers. It is not implemented for uWSGI, in the same way it isn't implemented for gunicorn. When you use uWSGI or gunicorn you have to start the server as you always do, but there are some restrictions on the options that you use (i.e. you have to enable gevent and websocket, and run a single worker, see the docs for an example).

Do I need to somehow run socketio.run(app) when I'm interfacing with uWSGI?

No, the run() method isn't used with uWSGI, at least not at this time.

Further, I don't really understand the init_app style you mention briefly.

init_app is a standard way to initialize Flask extensions that works well with the app factory pattern. See https://flask.palletsprojects.com/en/1.1.x/extensiondev/#the-extension-code.

wfehrnstrom

comment created time in 8 days

issue commentmiguelgrinberg/Flask-SocketIO

Not working as WebSocket on Windows 7 Ultimate

First of all, even if it was true that this package does not work under Windows 7, it is such an old release that I would not consider it important to support it.

But I believe you must be incorrect. Say that the logs show nothing is strange. If you connect to your webserver it should say something, even if it is an error. This is more likely user error on your part, but you need to provide more details about how you are connecting to help me pinpoint what you are doing wrong.

fred913

comment created time in 9 days

issue commentmiguelgrinberg/Flask-SocketIO

Flask stream_with_context blocking after changing to SocketIO

Something that you are doing in your generator is blocking eventlet. Monkey patching is likely to help. If that does not work, you should share more details on the work that you do in that streaming response. Maybe you will need to redesign it so that it is friendly to eventlet.

welabbar1

comment created time in 9 days

issue commentmiguelgrinberg/Flask-SocketIO

How i save and show existing progress status using flask socketio if browser is closed(session)

Do your clients authenticate? If they do, then when the client reopens the page you should be able to find if there are any pending tasks for that user.

Set4now

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Sending image to client without receiving the image from client.

Use JavaScript to update the src attribute of your <img> tag.

iszzul

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Does flask-socketio multiple server only support 2 servers?

Sorry, I don't understand what you are asking. Each server is an independent process. If you want to run two servers, then you run the application two times. To run a third server you run one more instance of the application. Each will be running on a different port, and you will use a reverse proxy such as nginx to load balance requests. See the docs if you need more information about this.

sbqsbqsbq

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Does flask-socketio multiple server only support 2 servers?

You can run as many servers as you need, there is no limit set to 2. Did you try running a 3rd server?

sbqsbqsbq

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Sending image to client without receiving the image from client.

You can call it an API if you like, but it is no different than any other endpoint that returns an image, such as those that return static files. Then from the client side you can generate an <img> tag that pulls this image into your page.

iszzul

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Nginx SSL - Not working

The docs are correct, the /socket.io path needs to be added to the proxy_pass statement.

I find it odd that you are getting a 400 error as a timeout, since 400 is not the correct code for timeouts, it should have been a 5xx code if it was really a timeout.

Try adding logging to the Socket.IO server to see if there are any useful messages there.

toomuchio

comment created time in 10 days

issue commentmiguelgrinberg/Flask-SocketIO

Sending image to client without receiving the image from client.

If this is a standard image, isn't it easier to serve it as a regular image file through the HTTP web server? Why do you need Socket.IO for this? You can send a notification to the client that there is a new image if you like, but the image itself could still go through HTTP.

iszzul

comment created time in 10 days

issue commentmiguelgrinberg/python-socketio

"ValueError: signal only works in main thread" when using the server

Ah yes, sorry, I missed it, this one needs to be fixed as well.

pcmoritz

comment created time in 10 days

issue commentmiguelgrinberg/flasky

I dont recieve any confirmation email

Did you look at the output of the application? If you run in debug mode you will see all the communication with the email server. If there is an error you should find clues there.

hammadi3

comment created time in 10 days

issue closedmiguelgrinberg/Flask-SocketIO

Integrating Flask Socket.io with Unreal engine 4 (UE4)

When trying to test the connection between UE4 and flask socket.io, there was an error number 400.

Here is the code that I tested. from flask import Flask, render_template, request from flask_socketio import SocketIO, emit

app = Flask(name) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, cors_allowed_origins='*')

@app.route('/') def index(): return render_template('index.html')

@socketio.on('chat message') def handle_my_custom_event(data): print(request.sid) print('received json: ' + str(data)) emit('chat message', data, broadcast=True)

if name == 'main': socketio.run(app)

closed time in 11 days

hghaffar2

issue commentmiguelgrinberg/Flask-SocketIO

NameError: name 'socketio' is not defined

You have defined socketio as a local variable in your run_app() function. Move it to a global variable above all the decorator usages and you should be fine.

Helveg

comment created time in 12 days

issue commentmiguelgrinberg/Flask-SocketIO

Server gets "stuck" and will not take incoming requests

If the monkey patching is done at the very start of the application, all imports of the affected packages should redirect to the alternative version. The problem is if monkey patching is not done first thing after start, then you may end up with weird behavior due to some blocking functions being used.

flabbyThoroughbred

comment created time in 12 days

issue commentmiguelgrinberg/Flask-SocketIO

Server gets "stuck" and will not take incoming requests

Are you sure subprocess.Popen is monkey patched? It would be useful to verify that, because if it isn't that would definitely block your server.

flabbyThoroughbred

comment created time in 12 days

issue commentmiguelgrinberg/python-engineio

Support for Set-Cookie response header from polling request

Okay, so if I understand this the problem occurs when you have some cookies given as a header and some more that are set during the HTTP transport exchange. So it works fine with one type of cookie or the other, but not with both together?

jackdreinhardt

comment created time in 12 days

issue commentmiguelgrinberg/python-engineio

Support for Set-Cookie response header from polling request

Then I'm confused. Cookies send by the server in the HTTP transport are already passed on the websocket connection. Here is the relevant code that moves the cookies from HTTP to WS: https://github.com/miguelgrinberg/python-engineio/blob/master/engineio/client.py#L355-L360.

Why do you think this isn't working for you?

jackdreinhardt

comment created time in 12 days

issue commentmiguelgrinberg/python-socketio

How to make socket.io Client keep listening to Node.js server messages?

Why do you send the token in the connection event handler? Isn't that before you have a token to send? Sorry, but I still think you are not telling me everything. I honestly see nothing wrong with the Socket.IO client. The rest I'm not sure I can't help, your JS logic is probably wrong.

DvDream

comment created time in 12 days

issue commentmiguelgrinberg/python-socketio

How to make socket.io Client keep listening to Node.js server messages?

When you say "after the login", what do you exactly mean? Nothing in your client script is logging in, unless you are showing just a snippet.

DvDream

comment created time in 13 days

issue commentmiguelgrinberg/python-socketio

How to make socket.io Client keep listening to Node.js server messages?

You know, just now I see what might be your problem. I missed the fact that your application is ending. To prevent the client from ending you have to use sio.wait(). Try the following:

import socketio

MAX_USERS = 1

num_of_users = 0
token_compiled = 'false'
users_tokens = np.array([])
users_headers = np.array([])

sio = socketio.Client()

@sio.event
def connect():
    print('connection established')


@sio.on('data')
def response(*args):
    print(args)
    global users_tokens
    users_tokens = np.append(users_tokens, args)

    
#Token collections
def do_something_with_tokens(users_tokens):
    for i in range(MAX_USERS):
        global users_headers,num_of_users
#        sio.sleep(4)
        users_headers = np.append(users_headers, {"Authorization": "Bearer %s"%users_tokens[i]})    
        num_of_users = num_of_users+1

if __name__=="__main__":
    sio.connect('http://localhost:8888')
    sio.wait()
DvDream

comment created time in 13 days

issue commentmiguelgrinberg/Flask-SocketIO

Server gets "stuck" and will not take incoming requests

What do you do in dl_submit_script? That's key to understand the problem. Based on your description my guess is that you are blocking there.

flabbyThoroughbred

comment created time in 13 days

more