Skip to content

Commit

Permalink
Feature/prospector (#255)
Browse files Browse the repository at this point in the history
* replace pylint withprospector

* force disable pep257/pep8, handled by black

* Fix tox ini
  • Loading branch information
michaelboulton committed Feb 26, 2019
1 parent e37e620 commit 54d3334
Show file tree
Hide file tree
Showing 25 changed files with 201 additions and 163 deletions.
16 changes: 11 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
repos:
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3.7
- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3.7
- repo: https://github.com/PyCQA/prospector
rev: 1.1.6 # The version of Prospector to use, at least 1.1.6
hooks:
- id: prospector
args:
- --strictness low
41 changes: 41 additions & 0 deletions .prospector.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
inherits:
- strictness_veryhigh

output-format: grouped

pep8:
none: true

# We only provide 1 function, this is a bit useless
doc-warnings: false

# Only enabled for pyflakes
test-warnings: false

dodgy:
run: true
profile-validator:
run: true
pyflakes:
run: true
pylint:
run: true
pyroma:
run: true

# Not needed
mccabe:
run: false
# Enabled in python 3 in tox
mypy:
run: false

ignore-paths:
- venv
- .tox
- docs
- example
- tests/integration
- build
- .pytest_cache
- tavern.egg_info
3 changes: 1 addition & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[MASTER]
disable=missing-docstring,bad-continuation,fixme,invalid-name,line-too-long,too-few-public-methods,no-else-return,too-many-branches

disable=missing-docstring,bad-continuation,fixme,invalid-name,line-too-long,too-few-public-methods,no-else-return,too-many-branches,locally-disabled,useless-object-inheritance
ignore=tests

[REPORTS]
Expand Down
10 changes: 6 additions & 4 deletions example/advanced/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@


def get_db():
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)

with db:
try:
db.execute("CREATE TABLE numbers_table (name TEXT NOT NULL, number INTEGER NOT NULL)")
db.execute(
"CREATE TABLE numbers_table (name TEXT NOT NULL, number INTEGER NOT NULL)"
)
except Exception:
pass

Expand All @@ -29,7 +31,7 @@ def get_db():

@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is not None:
db.close()

Expand All @@ -44,7 +46,7 @@ def login():
payload = {
"sub": "test-user",
"aud": SERVERNAME,
"exp": datetime.datetime.now() + datetime.timedelta(hours=1)
"exp": datetime.datetime.now() + datetime.timedelta(hours=1),
}

token = jwt.encode(payload, SECRET, algorithm="HS256").decode("utf8")
Expand Down
5 changes: 3 additions & 2 deletions example/components/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def login():
payload = {
"sub": "test-user",
"aud": SERVERNAME,
"exp": datetime.datetime.now() + datetime.timedelta(hours=1)
"exp": datetime.datetime.now() + datetime.timedelta(hours=1),
}

token = jwt.encode(payload, SECRET, algorithm="HS256").decode("utf8")
Expand Down Expand Up @@ -56,13 +56,14 @@ def check_auth_call(*args, **kwargs):

return check_auth_call


@app.route("/ping", methods=["GET"])
@requires_jwt
def ping():
return jsonify({"data": "pong"}), 200


@app.route("/hello/<name>", methods=["GET"])
@requires_jwt
def hello(name):
return jsonify({"data": "Hello, {}".format(name)}), 200

8 changes: 5 additions & 3 deletions example/cookies/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@


def get_db():
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)

with db:
try:
db.execute("CREATE TABLE numbers_table (name TEXT NOT NULL, number INTEGER NOT NULL)")
db.execute(
"CREATE TABLE numbers_table (name TEXT NOT NULL, number INTEGER NOT NULL)"
)
except:
pass

Expand All @@ -29,7 +31,7 @@ def get_db():

@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is not None:
db.close()

Expand Down
6 changes: 4 additions & 2 deletions example/generate_from_openapi/pub_tavern.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ def generate_tavern_yaml(json_path):
def output_yaml(links, prefix=""):
test_dict = {}
for test_name in links.keys():
default_name = get_name(prefix, test_name, links[test_name].action, links[test_name].url)
default_name = get_name(
prefix, test_name, links[test_name].action, links[test_name].url
)
test_dict["test_name"] = default_name

request = {
Expand All @@ -35,7 +37,7 @@ def output_yaml(links, prefix=""):
inner_dict = {"name": default_name, "request": request, "response": response}

test_dict["stages"] = [inner_dict]
#print(test_dict)
# print(test_dict)
print(yaml.dump(test_dict, explicit_start=True, default_flow_style=False))


Expand Down
39 changes: 20 additions & 19 deletions example/mqtt/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def get_client():


def get_db():
return sqlite3.connect(DATABASE)
return sqlite3.connect(DATABASE)


def setup_logging():
Expand Down Expand Up @@ -67,11 +67,18 @@ def handle_lights_topic(message):
if message.payload.decode("utf8") == "on":
logging.info("Lights have been turned on")
with db:
db.execute("UPDATE devices_table SET lights_on = 1 WHERE device_id IS (?)", (device_id,))
db.execute(
"UPDATE devices_table SET lights_on = 1 WHERE device_id IS (?)",
(device_id,),
)
elif message.payload.decode("utf8") == "off":
logging.info("Lights have been turned off")
with db:
db.execute("UPDATE devices_table SET lights_on = 0 WHERE device_id IS (?)", (device_id,))
db.execute(
"UPDATE devices_table SET lights_on = 0 WHERE device_id IS (?)",
(device_id,),
)


def handle_request_topic(client, message):
db = get_db()
Expand All @@ -80,7 +87,9 @@ def handle_request_topic(client, message):

logging.info("Checking lights status")
with db:
row = db.execute("SELECT lights_on FROM devices_table WHERE device_id IS (?)", (device_id,))
row = db.execute(
"SELECT lights_on FROM devices_table WHERE device_id IS (?)", (device_id,)
)

try:
status = int(next(row)[0])
Expand All @@ -89,25 +98,20 @@ def handle_request_topic(client, message):
else:
client.publish(
"/device/{}/status/response".format(device_id),
json.dumps({"lights": status})
json.dumps({"lights": status}),
)


def handle_ping_topic(client, message):
device_id = message.topic.split("/")[-2]

client.publish(
"/device/{}/pong".format(device_id),
)
client.publish("/device/{}/pong".format(device_id))


def handle_echo_topic(client, message):
device_id = message.topic.split("/")[-2]

client.publish(
"/device/{}/echo/response".format(device_id),
message.payload,
)
client.publish("/device/{}/echo/response".format(device_id), message.payload)


def on_message_callback(client, userdata, message):
Expand All @@ -131,12 +135,7 @@ def wait_for_messages():
mqtt_client.on_message = on_message_callback
mqtt_client.reconnect()

topics = [
"lights",
"ping",
"echo",
"status",
]
topics = ["lights", "ping", "echo", "status"]

for t in topics:
device_topic = "/device/{}/{}".format(123, t)
Expand All @@ -151,7 +150,9 @@ def wait_for_messages():

with db:
try:
db.execute("CREATE TABLE devices_table (device_id TEXT NOT NULL, lights_on INTEGER NOT NULL)")
db.execute(
"CREATE TABLE devices_table (device_id TEXT NOT NULL, lights_on INTEGER NOT NULL)"
)
except:
pass

Expand Down
12 changes: 4 additions & 8 deletions example/mqtt/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ def get_client():


def get_db():
return sqlite3.connect(DATABASE)
return sqlite3.connect(DATABASE)


def get_cached_db():
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is None:
db = g._database = get_db()

Expand Down Expand Up @@ -82,7 +82,7 @@ def setup_logging():

@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
db = getattr(g, "_database", None)
if db is not None:
db.close()

Expand All @@ -103,11 +103,7 @@ def send_message():

try:
with get_client() as mqtt_client:
mqtt_client.publish(
topic,
r["payload"],
r.get("qos", 0)
)
mqtt_client.publish(topic, r["payload"], r.get("qos", 0))
except Exception:
return jsonify({"error": topic}), 500

Expand Down
53 changes: 21 additions & 32 deletions example/remember/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,14 @@
from hashlib import sha512

app = Flask(__name__)
app.config.update(
SECRET_KEY = 'secret'
)
app.config.update(SECRET_KEY="secret")

users = {
'mark': {
'password': 'password',
'regular': 'foo',
'protected': 'bar'
}
}
users = {"mark": {"password": "password", "regular": "foo", "protected": "bar"}}

serializer = URLSafeTimedSerializer(
secret_key = 'secret',
salt = 'cookie',
signer_kwargs = dict(
key_derivation = 'hmac',
digest_method = sha512
)
secret_key="secret",
salt="cookie",
signer_kwargs=dict(key_derivation="hmac", digest_method=sha512),
)


Expand All @@ -32,38 +21,38 @@ def login():
username = r["username"]
password = r["password"]

if password == users[username]['password']:
session['user'] = username
response = make_response('', 200)
if password == users[username]["password"]:
session["user"] = username
response = make_response("", 200)
response.set_cookie(
'remember',
value = serializer.dumps(username),
expires = datetime.utcnow() + timedelta(days = 30),
httponly = True,
"remember",
value=serializer.dumps(username),
expires=datetime.utcnow() + timedelta(days=30),
httponly=True,
)
return response

return '', 401
return "", 401


@app.route("/regular", methods=["GET"])
def regular():
username = session.get('user')
username = session.get("user")

if not username:
remember = request.cookies.get('remember')
remember = request.cookies.get("remember")
if remember:
username = serializer.loads(remember, max_age = 3600)
username = serializer.loads(remember, max_age=3600)

if username:
return jsonify(regular = users[username]['regular']), 200
return jsonify(regular=users[username]["regular"]), 200

return '', 401
return "", 401


@app.route("/protected", methods=["GET"])
def protected():
username = session.get('user')
username = session.get("user")
if username:
return jsonify(protected = users[username]['protected']), 200
return '', 401
return jsonify(protected=users[username]["protected"]), 200
return "", 401

0 comments on commit 54d3334

Please sign in to comment.