Skip to content

Commit

Permalink
python 3 updates
Browse files Browse the repository at this point in the history
and some simplifications of conditional statements.
  • Loading branch information
marksmayo committed Nov 3, 2022
1 parent db0f471 commit 7ae5bdd
Show file tree
Hide file tree
Showing 56 changed files with 412 additions and 509 deletions.
17 changes: 3 additions & 14 deletions docs/_themes/flask_theme_support.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
# flasky extensions. flasky pygments style based on tango style
from pygments.style import Style
from pygments.token import (
Keyword,
Name,
Comment,
String,
Error,
Number,
Operator,
Generic,
Whitespace,
Punctuation,
Other,
Literal,
)
from pygments.token import (Comment, Error, Generic, Keyword, Literal, Name,
Number, Operator, Other, Punctuation, String,
Whitespace)


class FlaskyStyle(Style):
Expand Down
5 changes: 4 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os, datetime
import datetime
import os
import sys

import alabaster

# If extensions (or modules to document with autodoc) are in another directory,
Expand Down
9 changes: 6 additions & 3 deletions eve/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
:copyright: (c) 2017 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from flask import request, current_app as app, g, abort
from functools import wraps

from flask import abort
from flask import current_app as app
from flask import g, request


def requires_auth(endpoint_class):
"""Enables Authorization logic for decorated functions.
Expand Down Expand Up @@ -84,7 +87,7 @@ def decorated(*args, **kwargs):
return fdec


class BasicAuth(object):
class BasicAuth():
"""Implements Basic AUTH logic. Should be subclassed to implement custom
authentication checking.
Expand Down Expand Up @@ -214,7 +217,7 @@ def authorized(self, allowed_roles, resource, method):
try:
userid, hmac_hash = auth.split(":")
self.set_user_or_token(userid)
except:
except Exception:
auth = None
return auth and self.check_auth(
userid,
Expand Down
15 changes: 8 additions & 7 deletions eve/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
import re

from bson import tz_util
from flask import abort, request, current_app as app, Response
from flask import Response, abort
from flask import current_app as app
from flask import request

import eve
from eve.auth import requires_auth, resource_auth
from eve.methods import get, getitem, post, patch, delete, deleteitem, put
from eve.methods import delete, deleteitem, get, getitem, patch, post, put
from eve.methods.common import ratelimit
from eve.render import send_response
from eve.utils import config, weak_date, date_to_rfc1123
import eve
from eve.utils import config, date_to_rfc1123, weak_date


def collections_endpoint(**lookup):
Expand Down Expand Up @@ -154,8 +156,7 @@ def home_endpoint():

response[config.LINKS] = {"child": links}
return send_response(None, (response,))
else:
return send_response(None, (response,))
return send_response(None, (response,))


def error_endpoint(error):
Expand Down Expand Up @@ -216,7 +217,7 @@ def media_endpoint(_id):
begin, end = m.groups()
begin = int(begin)
end = int(end)
except:
except Exception:
begin, end = 0, None

length = size - begin
Expand Down
46 changes: 20 additions & 26 deletions eve/flaskapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,25 @@
:copyright: (c) 2017 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
import copy
import fnmatch
import os
import sys
import warnings

import copy
from events import Events
from flask import Flask
from werkzeug.routing import BaseConverter
from werkzeug.serving import WSGIRequestHandler

import eve
from eve import default_settings
from eve.endpoints import (
collections_endpoint,
item_endpoint,
home_endpoint,
error_endpoint,
media_endpoint,
schema_collection_endpoint,
schema_item_endpoint,
)
from eve.endpoints import (collections_endpoint, error_endpoint, home_endpoint,
item_endpoint, media_endpoint,
schema_collection_endpoint, schema_item_endpoint)
from eve.exceptions import ConfigException, SchemaException
from eve.io.mongo import Mongo, Validator, GridFSMediaStorage, ensure_mongo_indexes
from eve.io.mongo import (GridFSMediaStorage, Mongo, Validator,
ensure_mongo_indexes)
from eve.logging import RequestFilter
from eve.utils import api_prefix, extract_key_values

Expand All @@ -46,15 +41,15 @@ class EveWSGIRequestHandler(WSGIRequestHandler):
def server_version(self):
return (
"Eve/%s " % eve.__version__
+ super(EveWSGIRequestHandler, self).server_version
+ super().server_version
)


class RegexConverter(BaseConverter):
"""Extend werkzeug routing by supporting regex for urls/API endpoints"""

def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
super().__init__(url_map)
self.regex = items[0]


Expand Down Expand Up @@ -149,7 +144,7 @@ def __init__(
we need to enhance our super-class a little bit.
"""

super(Eve, self).__init__(import_name, **kwargs)
super().__init__(import_name, **kwargs)

# add support for request metadata to the log record
self.logger.addFilter(RequestFilter())
Expand Down Expand Up @@ -222,7 +217,7 @@ def run(self, host=None, port=None, debug=None, **options):
information."""

options.setdefault("request_handler", EveWSGIRequestHandler)
super(Eve, self).run(host, port, debug, **options)
super().run(host, port, debug, **options)

def load_config(self):
"""API settings are loaded from standard python modules. First from
Expand Down Expand Up @@ -259,14 +254,13 @@ def find_settings_file(file_name):
settings_file = os.path.join(abspath, file_name)
if os.path.isfile(settings_file):
return settings_file
else:
# try to find settings.py in one of the
# paths in sys.path
for p in sys.path:
for root, dirs, files in os.walk(p):
for f in fnmatch.filter(files, file_name):
if os.path.isfile(os.path.join(root, f)):
return os.path.join(root, file_name)
# try to find settings.py in one of the
# paths in sys.path
for p in sys.path:
for root, dirs, files in os.walk(p):
for f in fnmatch.filter(files, file_name):
if os.path.isfile(os.path.join(root, f)):
return os.path.join(root, file_name)

# try to load file from environment variable or settings.py
pyfile = find_settings_file(
Expand All @@ -278,7 +272,7 @@ def find_settings_file(file_name):

try:
self.config.from_pyfile(pyfile)
except:
except Exception:
raise

# flask-pymongo compatibility
Expand Down Expand Up @@ -319,7 +313,7 @@ def validate_domain_struct(self):
"""
try:
domain = self.config["DOMAIN"]
except:
except Exception:
raise ConfigException("DOMAIN dictionary missing or wrong.")
if not isinstance(domain, dict):
raise ConfigException("DOMAIN must be a dict.")
Expand Down Expand Up @@ -1107,4 +1101,4 @@ def __call__(self, environ, start_response):
environ["REQUEST_METHOD"] = environ.get(
"HTTP_X_HTTP_METHOD_OVERRIDE", environ["REQUEST_METHOD"]
).upper()
return super(Eve, self).__call__(environ, start_response)
return super().__call__(environ, start_response)
2 changes: 1 addition & 1 deletion eve/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
"""

# flake8: noqa
from eve.io.base import DataLayer, ConnectionException
from eve.io.base import ConnectionException, DataLayer
17 changes: 9 additions & 8 deletions eve/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
:license: BSD, see LICENSE for more details.
"""
import datetime
import simplejson as json
from copy import copy
from flask import request, abort
from eve.utils import date_to_str

import simplejson as json
from flask import abort, request

from eve.auth import auth_field_and_value
from eve.utils import config, auto_fields, debug_error_message
from eve.utils import auto_fields, config, date_to_str, debug_error_message


class BaseJSONEncoder(json.JSONEncoder):
Expand All @@ -27,11 +28,11 @@ def default(self, obj):
if isinstance(obj, datetime.datetime):
# convert any datetime to RFC 1123 format
return date_to_str(obj)
elif isinstance(obj, (datetime.time, datetime.date)):
if isinstance(obj, (datetime.time, datetime.date)):
# should not happen since the only supported date-like format
# supported at dmain schema level is 'datetime' .
return obj.isoformat()
elif isinstance(obj, set):
if isinstance(obj, set):
# convert set objects to encodable lists
return list(obj)
return json.JSONEncoder.default(self, obj)
Expand All @@ -58,7 +59,7 @@ def __str__(self):
return msg


class DataLayer(object):
class DataLayer():
"""Base data layer class. Defines the interface that actual data-access
classes, being subclasses, must implement. Implemented as a Flask
extension.
Expand Down Expand Up @@ -528,7 +529,7 @@ def _client_projection(self, req):
client_projection = json.loads(req.projection)
if not isinstance(client_projection, dict):
raise Exception("The projection parameter has to be a " "dict")
except:
except Exception:
abort(
400,
description=debug_error_message(
Expand Down
2 changes: 1 addition & 1 deletion eve/io/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"""


class MediaStorage(object):
class MediaStorage():
"""The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
Expand Down
2 changes: 1 addition & 1 deletion eve/io/mongo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
:license: BSD, see LICENSE for more details.
"""

from eve.io.mongo.media import GridFSMediaStorage
# flake8: noqa
from eve.io.mongo.mongo import Mongo, MongoJSONEncoder, ensure_mongo_indexes
from eve.io.mongo.validation import Validator
from eve.io.mongo.media import GridFSMediaStorage
2 changes: 1 addition & 1 deletion eve/io/mongo/flask_pymongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from pymongo import MongoClient, uri_parser


class PyMongo(object):
class PyMongo():
"""
Creates Mongo connection and database based on Flask configuration.
"""
Expand Down
20 changes: 10 additions & 10 deletions eve/io/mongo/geo.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def _correct_position(self, position):

class Geometry(GeoJSON):
def __init__(self, json):
super(Geometry, self).__init__(json)
super().__init__(json)
try:
if (
not isinstance(self["coordinates"], list)
Expand All @@ -45,7 +45,7 @@ def __init__(self, json):

class GeometryCollection(GeoJSON):
def __init__(self, json):
super(GeometryCollection, self).__init__(json)
super().__init__(json)
try:
if not isinstance(self["geometries"], list):
raise TypeError
Expand All @@ -58,30 +58,30 @@ def __init__(self, json):

class Point(Geometry):
def __init__(self, json):
super(Point, self).__init__(json)
super().__init__(json)
if not self._correct_position(self["coordinates"]):
raise TypeError


class MultiPoint(GeoJSON):
def __init__(self, json):
super(MultiPoint, self).__init__(json)
super().__init__(json)
for position in self["coordinates"]:
if not self._correct_position(position):
raise TypeError


class LineString(GeoJSON):
def __init__(self, json):
super(LineString, self).__init__(json)
super().__init__(json)
for position in self["coordinates"]:
if not self._correct_position(position):
raise TypeError


class MultiLineString(GeoJSON):
def __init__(self, json):
super(MultiLineString, self).__init__(json)
super().__init__(json)
for linestring in self["coordinates"]:
for position in linestring:
if not self._correct_position(position):
Expand All @@ -90,7 +90,7 @@ def __init__(self, json):

class Polygon(GeoJSON):
def __init__(self, json):
super(Polygon, self).__init__(json)
super().__init__(json)
for linestring in self["coordinates"]:
for position in linestring:
if not self._correct_position(position):
Expand All @@ -99,7 +99,7 @@ def __init__(self, json):

class MultiPolygon(GeoJSON):
def __init__(self, json):
super(MultiPolygon, self).__init__(json)
super().__init__(json)
for polygon in self["coordinates"]:
for linestring in polygon:
for position in linestring:
Expand All @@ -109,7 +109,7 @@ def __init__(self, json):

class Feature(GeoJSON):
def __init__(self, json):
super(Feature, self).__init__(json)
super().__init__(json)
try:
geometry = self["geometry"]
factory = factories[geometry["type"]]
Expand All @@ -121,7 +121,7 @@ def __init__(self, json):

class FeatureCollection(GeoJSON):
def __init__(self, json):
super(FeatureCollection, self).__init__(json)
super().__init__(json)
try:
if not isinstance(self["features"], list):
raise TypeError
Expand Down
Loading

0 comments on commit 7ae5bdd

Please sign in to comment.