Merge pull request 'refactor to get_default_db' (#1) from songmeo/doorboy-proxy:master into master

Reviewed-on: http://git.k-space.ee/k-space/doorboy-proxy/pulls/1
This commit is contained in:
Lauri Võsandi 2021-04-04 08:52:19 +00:00
commit 0e2f3aef1f
5 changed files with 64 additions and 35 deletions

View File

@ -5,4 +5,4 @@ COPY requirements.txt ./
RUN pip install -r requirements.txt RUN pip install -r requirements.txt
COPY *.py ./ COPY *.py ./
CMD ["gunicorn", "--workers", "10", "--bind", "[::]:5000", "main:app", "--timeout", "90"] CMD ["gunicorn", "--worker-class", "sanic.worker.GunicornWorker", "--workers", "10", "--bind", "[::]:5000", "main:app", "--timeout", "90"]

2
const.py Normal file
View File

@ -0,0 +1,2 @@
import os
MONGO_URI = os.getenv("MONGO_URI", "mongodb://127.0.0.1:27017/kspace_accounting")

26
dev.yml Normal file
View File

@ -0,0 +1,26 @@
version: '3.7'
services:
mongoexpress:
image: mongo-express
network_mode: host
environment:
- ME_CONFIG_MONGODB_ENABLE_ADMIN=true
- ME_CONFIG_MONGODB_SERVER=127.0.0.1
- ME_CONFIG_MONGODB_PORT=27017
- ME_CONFIG_MONGODB_AUTH_DATABASE=admin
mongo:
network_mode: host
restart: unless-stopped
image: mongo:latest
environment:
- MONGODB_INITDB_ROOT_USERNAME=doorboy
- MONGODB_INITDB_ROOT_PASSWORD=password
- MONGODB_INITDB_DATABASE=kspace_accounting
doorboy_proxy:
hostname: doorboy.infra.k-space.ee
restart: unless-stopped
network_mode: host
env_file: .env
build:
context: .

64
main.py
View File

@ -1,43 +1,45 @@
from datetime import datetime from datetime import datetime
from flask import Flask, request, redirect, render_template, Blueprint, make_response, jsonify from sanic import Sanic, response
from pymongo import MongoClient from sanic.response import text, json, stream
import flask from motor.motor_asyncio import AsyncIOMotorClient
import hashlib import uvloop, asyncio
import jinja2
import json
import os
import pymongo import pymongo
import smtplib import os
import const
app = Flask(__name__) app = Sanic(__name__)
mongodb = MongoClient('mongodb://172.21.27.1,172.21.27.2,172.21.27.3:27017/', replicaSet="kspace-mongo-set").kspace_accounting
mongodb.authenticate("kspace_accounting", os.environ["MONGO_PASSWORD"]) #mongodb = MongoClient('mongodb://172.21.27.1,172.21.27.2,172.21.27.3:27017/', replicaSet="kspace-mongo-set").kspace_accounting
mongodb = AsyncIOMotorClient(const.MONGO_URI)
mongodb = mongodb.get_default_database()
DOORBOY_SECRET = os.environ["DOORBOY_SECRET"] DOORBOY_SECRET = os.environ["DOORBOY_SECRET"]
assert len(DOORBOY_SECRET) > 10 assert len(DOORBOY_SECRET) > 10
@app.route("/allowed") @app.route("/allowed")
def view_doorboy_uids(): async def view_doorboy_uids(request):
if request.headers.get('KEY') != DOORBOY_SECRET: if request.headers.get('KEY') != DOORBOY_SECRET:
return "how about no" return text("how about no")
allowed_names = [o["_id"] for o in mongodb.member.find({"enabled": True})] allowed_names = []
async for obj in mongodb.member.find({"enabled": True}):
allowed_names.append(obj["_id"])
allowed_uids = [] allowed_uids = []
for obj in mongodb.inventory.find({"token.uid_hash": {"$exists":True}, "inventory.owner_id": {"$exists":True}, "token.enabled": True}, {"inventory.owner_id": True, "token.uid_hash": True }): async for obj in mongodb.inventory.find({"token.uid_hash": {"$exists":True}, "inventory.owner_id": {"$exists":True}, "token.enabled": True}, {"inventory.owner_id": True, "token.uid_hash": True }):
if obj["inventory"].pop("owner_id") in allowed_names: if obj["inventory"].pop("owner_id") in allowed_names:
obj.pop("_id") del obj["_id"]
obj.pop("inventory") del obj["inventory"]
allowed_uids.append(obj) allowed_uids.append(obj)
return jsonify(allowed_uids=allowed_uids) return json({"allowed_uids": allowed_uids})
@app.route("/longpoll") @app.route("/longpoll")
def view_longpoll(): async def view_longpoll(request):
if request.headers.get('KEY') != DOORBOY_SECRET: if request.headers.get('KEY') != DOORBOY_SECRET:
return "how about no" return text("how about no")
def g(): async def g(response):
yield "data: response-generator-started\n\n" await response.write("data: response-generator-started\n\n")
pipeline = [ pipeline = [
{ {
'$match': { '$match': {
@ -48,16 +50,16 @@ def view_longpoll():
} }
] ]
try: try:
with mongodb.eventlog.watch(pipeline) as stream: async with mongodb.eventlog.watch(pipeline) as stream:
yield "data: watch-stream-opened\n\n" await response.write("data: watch-stream-opened\n\n")
for event in stream: async for event in stream:
if event["fullDocument"].get("type") == "open-door": if event["fullDocument"].get("type") == "open-door":
yield "data: %s\n\n" % event["fullDocument"]["door"] await response.write("data: %s\n\n" % event["fullDocument"]["door"])
except pymongo.errors.PyMongoError: except pymongo.errors.PyMongoError:
return "urror" return
return flask.Response(g(), return stream(g, content_type="text/event-stream")
mimetype="text/event-stream")
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=False, host='::') asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # swap default event loop to uvloop
loop = asyncio.get_event_loop()
app.run(host='::', debug=False, loop=loop)

View File

@ -1,4 +1,3 @@
Flask
Flask-WTF
pymongo
gunicorn gunicorn
sanic
motor