fix example to work on python3

* fix longpoll example

* fix websocket example

* fix django example

* fix flask exampl
This commit is contained in:
Benoit Chesneau 2018-09-04 09:57:24 +02:00
parent e974f30517
commit c16abf922e
7 changed files with 60 additions and 32 deletions

View File

@ -3,7 +3,7 @@ import io
import os
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.template import RequestContext
@ -38,12 +38,14 @@ def home(request):
else:
form = MsgForm()
return render_to_response('home.html', {
return render(request, 'home.html', {
'form': form,
'subject': subject,
'message': message,
'size': size
}, RequestContext(request))
})
def acsv(request):

View File

@ -81,7 +81,8 @@ STATICFILES_FINDERS = (
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
SECRET_KEY = 'what'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
@ -107,6 +108,17 @@ ROOT_URLCONF = 'testing.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'testing.wsgi.application'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.

View File

@ -13,7 +13,7 @@ urlpatterns = [
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/', admin.site.urls),
url(r'^', include("testing.apps.someapp.urls")),
]

View File

@ -7,7 +7,7 @@ app = Flask(__name__)
@app.route('/')
def index():
buf = io.BytesIO()
buf.write('hello world')
buf.write(b'hello world')
buf.seek(0)
return send_file(buf,
attachment_filename="testing.txt",

View File

@ -10,7 +10,7 @@ import time
class TestIter(object):
def __iter__(self):
lines = ['line 1\n', 'line 2\n']
lines = [b'line 1\n', b'line 2\n']
for line in lines:
yield line
time.sleep(20)

View File

@ -2,7 +2,7 @@
import collections
import errno
import re
from hashlib import sha1
import hashlib
import base64
from base64 import b64encode, b64decode
import socket
@ -11,11 +11,11 @@ import logging
from socket import error as SocketError
import gevent
from gunicorn.workers.async import ALREADY_HANDLED
from gunicorn.workers.base_async import ALREADY_HANDLED
logger = logging.getLogger(__name__)
WS_KEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
class WebSocketWSGI(object):
def __init__(self, handler):
@ -80,6 +80,10 @@ class WebSocketWSGI(object):
if ws_extensions:
handshake_reply += 'Sec-WebSocket-Extensions: %s\r\n' % ', '.join(ws_extensions)
key_hash = hashlib.sha1()
key_hash.update(key.encode())
key_hash.update(WS_KEY)
handshake_reply += (
"Sec-WebSocket-Origin: %s\r\n"
"Sec-WebSocket-Location: ws://%s%s\r\n"
@ -90,7 +94,7 @@ class WebSocketWSGI(object):
environ.get('HTTP_HOST'),
ws.path,
version,
base64.b64encode(sha1(key + WS_KEY).digest())
base64.b64encode(key_hash.digest()).decode()
))
else:
@ -102,13 +106,14 @@ class WebSocketWSGI(object):
environ.get('HTTP_HOST'),
ws.path))
sock.sendall(handshake_reply)
sock.sendall(handshake_reply.encode())
try:
self.handler(ws)
except socket.error as e:
if e[0] != errno.EPIPE:
raise
except BrokenPipeError:
pass
else:
raise
# use this undocumented feature of grainbows to ensure that it
# doesn't barf on the fact that we didn't call start_response
return ALREADY_HANDLED
@ -163,6 +168,8 @@ class WebSocket(object):
"""
if base64:
buf = b64encode(buf)
else:
buf = buf.encode()
b1 = 0x80 | (opcode & 0x0f) # FIN + opcode
payload_len = len(buf)
@ -375,7 +382,7 @@ class WebSocket(object):
return None
# no parsed messages, must mean buf needs more data
delta = self.socket.recv(8096)
if delta == '':
if delta == b'':
return None
self._buf += delta
msgs = self._parse_messages()
@ -395,7 +402,7 @@ class WebSocket(object):
elif self.version == 76 and not self.websocket_closed:
try:
self.socket.sendall("\xff\x00")
self.socket.sendall(b"\xff\x00")
except SocketError:
# Sometimes, like when the remote side cuts off the connection,
# we don't care about this.
@ -425,7 +432,7 @@ def handle(ws):
ws.send(m)
elif ws.path == '/data':
for i in xrange(10000):
for i in range(10000):
ws.send("0 %s %s\n" % (i, random.random()))
gevent.sleep(0.1)
@ -439,7 +446,7 @@ def app(environ, start_response):
'websocket.html')).read()
data = data % environ
start_response('200 OK', [('Content-Type', 'text/html'),
('Content-Length', len(data))])
return [data]
('Content-Length', str(len(data)))])
return [data.encode()]
else:
return wsapp(environ, start_response)

View File

@ -11,12 +11,12 @@ import logging
from socket import error as SocketError
import eventlet
from gunicorn.workers.async import ALREADY_HANDLED
from gunicorn.workers.base_async import ALREADY_HANDLED
from eventlet import pools
logger = logging.getLogger(__name__)
WS_KEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
class WebSocketWSGI(object):
def __init__(self, handler):
@ -81,6 +81,10 @@ class WebSocketWSGI(object):
if ws_extensions:
handshake_reply += 'Sec-WebSocket-Extensions: %s\r\n' % ', '.join(ws_extensions)
key_hash = sha1()
key_hash.update(key.encode())
key_hash.update(WS_KEY)
handshake_reply += (
"Sec-WebSocket-Origin: %s\r\n"
"Sec-WebSocket-Location: ws://%s%s\r\n"
@ -91,7 +95,7 @@ class WebSocketWSGI(object):
environ.get('HTTP_HOST'),
ws.path,
version,
base64.b64encode(sha1(key + WS_KEY).digest())
base64.b64encode(key_hash.digest()).decode()
))
else:
@ -103,13 +107,14 @@ class WebSocketWSGI(object):
environ.get('HTTP_HOST'),
ws.path))
sock.sendall(handshake_reply)
sock.sendall(handshake_reply.encode())
try:
self.handler(ws)
except socket.error as e:
if e[0] != errno.EPIPE:
raise
except BrokenPipeError:
pass
else:
raise
# use this undocumented feature of grainbows to ensure that it
# doesn't barf on the fact that we didn't call start_response
return ALREADY_HANDLED
@ -164,6 +169,8 @@ class WebSocket(object):
"""
if base64:
buf = b64encode(buf)
else:
buf = buf.encode()
b1 = 0x80 | (opcode & 0x0f) # FIN + opcode
payload_len = len(buf)
@ -376,7 +383,7 @@ class WebSocket(object):
return None
# no parsed messages, must mean buf needs more data
delta = self.socket.recv(8096)
if delta == '':
if delta == b'':
return None
self._buf += delta
msgs = self._parse_messages()
@ -396,7 +403,7 @@ class WebSocket(object):
elif self.version == 76 and not self.websocket_closed:
try:
self.socket.sendall("\xff\x00")
self.socket.sendall(b"\xff\x00")
except SocketError:
# Sometimes, like when the remote side cuts off the connection,
# we don't care about this.
@ -425,7 +432,7 @@ def handle(ws):
ws.send(m)
elif ws.path == '/data':
for i in xrange(10000):
for i in range(10000):
ws.send("0 %s %s\n" % (i, random.random()))
eventlet.sleep(0.1)
@ -439,7 +446,7 @@ def app(environ, start_response):
'websocket.html')).read()
data = data % environ
start_response('200 OK', [('Content-Type', 'text/html'),
('Content-Length', len(data))])
return [data]
('Content-Length', str(len(data)))])
return [data.encode()]
else:
return wsapp(environ, start_response)