Skip to content

Commit

Permalink
Codechange: Update to bottle 0.12.25 (#155)
Browse files Browse the repository at this point in the history
Retains previous modifications
  • Loading branch information
LordAro authored Sep 12, 2023
1 parent 930935d commit 93728fc
Showing 1 changed file with 59 additions and 21 deletions.
80 changes: 59 additions & 21 deletions webtranslate/bottle.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from __future__ import with_statement

__author__ = 'Marcel Hellkamp'
__version__ = '0.12.18-eints'
__version__ = '0.12.25-eints'
__license__ = 'MIT'

# The gevent server adapter needs to patch some modules before they are imported
Expand All @@ -47,7 +47,6 @@
from datetime import date as datedate, datetime, timedelta
from tempfile import TemporaryFile
from traceback import format_exc, print_exc
from inspect import getargspec
from unicodedata import normalize

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -101,6 +100,12 @@ def _e(): return sys.exc_info()[1]
import pickle
from io import BytesIO
from configparser import ConfigParser
from inspect import getfullargspec
def getargspec(func):
spec = getfullargspec(func)
kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs)
return kwargs, spec[1], spec[2], spec[3]

basestring = str
unicode = str
json_loads = lambda s: json_lds(touni(s))
Expand All @@ -118,6 +123,7 @@ def _raise(*a): raise a[0](a[1]).with_traceback(a[2])
from imp import new_module
from StringIO import StringIO as BytesIO
from ConfigParser import SafeConfigParser as ConfigParser
from inspect import getargspec
if py25:
msg = "Python 2.5 support may be dropped in future versions of Bottle."
warnings.warn(msg, DeprecationWarning)
Expand Down Expand Up @@ -310,7 +316,7 @@ def add_filter(self, name, func):
rule_syntax = re.compile('(\\\\*)'\
'(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'\
'|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'\
'(?::((?:\\\\.|[^\\\\>]+)+)?)?)?>))')
'(?::((?:\\\\.|[^\\\\>])+)?)?)?>))')

def _itertokens(self, rule):
offset, prefix = 0, ''
Expand Down Expand Up @@ -567,7 +573,7 @@ def get_callback_args(self):
def get_config(self, key, default=None):
''' Lookup a config field and return its value, first checking the
route.config, then route.app.config.'''
for conf in (self.config, self.app.conifg):
for conf in (self.config, self.app.config):
if key in conf: return conf[key]
return default

Expand Down Expand Up @@ -856,17 +862,19 @@ def default_error_handler(self, res):
return tob(template(ERROR_PAGE_TEMPLATE, e=res))

def _handle(self, environ):
path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')

try:

environ['bottle.app'] = self
request.bind(environ)
response.bind()

path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')

try:
self.trigger_hook('before_request')
route, args = self.router.match(environ)
Expand Down Expand Up @@ -1098,6 +1106,7 @@ def forms(self):
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = FormsDict()
forms.recode_unicode = self.POST.recode_unicode
for name, item in self.POST.allitems():
if not isinstance(item, FileUpload):
forms[name] = item
Expand All @@ -1121,6 +1130,7 @@ def files(self):
"""
files = FormsDict()
files.recode_unicode = self.POST.recode_unicode
for name, item in self.POST.allitems():
if isinstance(item, FileUpload):
files[name] = item
Expand Down Expand Up @@ -1246,15 +1256,16 @@ def POST(self):
newline='\n')
elif py3k:
args['encoding'] = 'utf8'
post.recode_unicode = False
data = cgi.FieldStorage(**args)
self['_cgi.FieldStorage'] = data #http://bugs.python.org/issue18394#msg207958
data = data.list or []
for item in data:
if item.filename:
if item.filename is None:
post[item.name] = item.value
else:
post[item.name] = FileUpload(item.file, item.name,
item.filename, item.headers)
else:
post[item.name] = item.value
return post

@property
Expand Down Expand Up @@ -1757,7 +1768,7 @@ def apply(self, callback, route):
def wrapper(*a, **ka):
try:
rv = callback(*a, **ka)
except HTTPError:
except HTTPResponse:
rv = _e()

if isinstance(rv, dict):
Expand Down Expand Up @@ -2596,7 +2607,7 @@ def parse_range_header(header, maxlen=0):

def _parse_qsl(qs):
r = []
for pair in qs.replace(';','&').split('&'):
for pair in qs.split('&'):
if not pair: continue
nv = pair.split('=', 1)
if len(nv) != 2: nv.append('')
Expand Down Expand Up @@ -2700,6 +2711,7 @@ def auth_basic(check, realm="private", text="Access denied"):
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
@functools.wraps(func)
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or not check(user, password):
Expand Down Expand Up @@ -2806,7 +2818,11 @@ class server_cls(server_cls):

class CherryPyServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from cherrypy import wsgiserver
depr("The wsgi server part of cherrypy was split into a new "
"project called 'cheroot'. Use the 'cheroot' server "
"adapter instead of cherrypy.")
from cherrypy import wsgiserver # This will fail for CherryPy >= 9

self.options['bind_addr'] = (self.host, self.port)
self.options['wsgi_app'] = handler

Expand All @@ -2829,6 +2845,25 @@ def run(self, handler): # pragma: no cover
server.stop()


class CherootServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from cheroot import wsgi
from cheroot.ssl import builtin
self.options['bind_addr'] = (self.host, self.port)
self.options['wsgi_app'] = handler
certfile = self.options.pop('certfile', None)
keyfile = self.options.pop('keyfile', None)
chainfile = self.options.pop('chainfile', None)
server = wsgi.Server(**self.options)
if certfile and keyfile:
server.ssl_adapter = builtin.BuiltinSSLAdapter(
certfile, keyfile, chainfile)
try:
server.start()
finally:
server.stop()


class WaitressServer(ServerAdapter):
def run(self, handler):
from waitress import serve
Expand All @@ -2852,7 +2887,7 @@ def run(self, handler):


class FapwsServer(ServerAdapter):
""" Extremely fast webserver using libev. See http://www.fapws.org/ """
""" Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3 """
def run(self, handler): # pragma: no cover
import fapws._evwsgi as evwsgi
from fapws import base, config
Expand Down Expand Up @@ -2996,7 +3031,9 @@ def run(self, handler):

class AutoServer(ServerAdapter):
""" Untested. """
adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer, WSGIRefServer]
adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer,
CherootServer, WSGIRefServer]

def run(self, handler):
for sa in self.adapters:
try:
Expand All @@ -3010,6 +3047,7 @@ def run(self, handler):
'wsgiref': WSGIRefServer,
'waitress': WaitressServer,
'cherrypy': CherryPyServer,
'cheroot': CherootServer,
'paste': PasteServer,
'fapws3': FapwsServer,
'tornado': TornadoServer,
Expand Down Expand Up @@ -3464,7 +3502,7 @@ class StplParser(object):
# Match the start tokens of code areas in a template
_re_split = '(?m)^[ \t]*(\\\\?)((%(line_start)s)|(%(block_start)s))(%%?)'
# Match inline statements (may contain python strings)
_re_inl = '(?m)%%(inline_start)s((?:%s|[^\'"\n]*?)+)%%(inline_end)s' % _re_inl
_re_inl = '(?m)%%(inline_start)s((?:%s|[^\'"\n])*?)%%(inline_end)s' % _re_inl
_re_tok = '(?m)' + _re_tok

default_syntax = '<% %> % {{ }}'
Expand Down Expand Up @@ -3666,7 +3704,7 @@ def wrapper(*args, **kwargs):
tplvars.update(result)
return template(tpl_name, **tplvars)
elif result is None:
return template(tpl_name, defaults)
return template(tpl_name, **defaults)
return result
return wrapper
return decorator
Expand Down

0 comments on commit 93728fc

Please sign in to comment.