-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
144 lines (116 loc) · 3.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
Watchtower Web Server
"""
__author__ = 'Enis Simsar'
import json
from models.Invitation import InvitationSchema
from models.News import NewsSchema
from models.Topic import TopicSchema
from models.Tweet import TweetSchema
from models.User import UserSchema, User, hash_password
import tornado.ioloop
from tornado.options import options
import tornado.web
from decouple import config
from settings import app_settings
from urls import url_patterns
from logging import handlers
import logging
from mongoengine import connect, DoesNotExist
import time
import os
from apispec import APISpec
from apispec.ext.tornado import TornadoPlugin
from apispec.ext.marshmallow import MarshmallowPlugin
os.makedirs('./logs', exist_ok=True)
log_file = "./logs/daily_" + time.strftime("%d-%m-%Y") + ".log"
daily_handler = handlers.TimedRotatingFileHandler(
log_file,
when='midnight',
interval=1,
backupCount=7
)
logging.basicConfig(
level=logging.INFO,
format="[%(levelname)s %(asctime)s %(pathname)s@%(funcName)s:%(lineno)s] %(message)s",
datefmt="%d/%m/%Y %H:%M:%S",
handlers=[
daily_handler,
logging.StreamHandler()
],
)
spec = APISpec(
title='WatchTower News API',
version='1.0.0',
openapi_version='2.0',
plugins=(
TornadoPlugin(),
MarshmallowPlugin(),
),
info=dict(
description='Default api token is "welcome_to_watchtower_news_api" Please, add this token to your header '
'X-API-Key: "welcome_to_watchtower_news_api" '
),
securityDefinitions=dict(
apiKey={
'type': 'apiKey',
'name': 'X-API-Key',
'in': 'header',
'description': 'API Key for Authorization'
}
),
options={
'consumes': ['application/json'],
'produces': ['application/json']
}
)
# spec.definition('User', schema=UserSchema)
spec.definition('Topic', schema=TopicSchema)
# spec.definition('Invitation', schema=InvitationSchema)
spec.definition('News', schema=NewsSchema)
# spec.definition('Tweet', schema=TweetSchema)
for url_path in url_patterns:
if 'api' in url_path[0]:
spec.add_path(urlspec=url_path)
continue
with open('./static/data.json', 'w') as outfile:
json.dump(spec.to_dict(), outfile)
def add_admin_user():
data = {
'username': 'admin',
'password': hash_password('123456'),
'api_token': 'welcome_to_watchtower_news_api'
}
try:
user = User(**data)
user.save()
except Exception as e:
logging.error("exception: {0}".format(str(e)))
class WatchtowerNewsApp(tornado.web.Application):
def __init__(self, testing=False):
super(WatchtowerNewsApp, self).__init__(url_patterns, **app_settings, autoreload=not testing)
def main():
options.parse_command_line()
logging.getLogger('tornado.access').disabled = True
app = WatchtowerNewsApp()
app.listen(app_settings["port"])
connect(
config('MONGODB_DB'),
username=config('MONGODB_USER'),
password=config('MONGODB_PASSWORD'),
host=config('MONGODB_HOST'),
port=config('MONGODB_PORT', cast=int),
authentication_source='admin',
connect=False
)
try:
u = User.objects.filter(username='admin')
if not len(u):
add_admin_user()
except DoesNotExist:
add_admin_user()
except Exception as e:
pass
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()