-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
62 lines (48 loc) · 1.58 KB
/
utils.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
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# psychedelizer.0x80.ru
# utils.py (c) Mikhail Mezyakov <[email protected]>
#
# Some utils
from datetime import datetime
def from_unix(unixtime):
"""Convert unixtime to readable datetime string"""
return datetime.fromtimestamp(float(unixtime)).strftime('%Y-%m-%d %H:%M:%S')
def get_ip(request):
"""Return ip from HTTP headers. If it's empty, return remote_ip from request instance"""
if 'X-Real-Ip' in request.headers:
ip = request.headers['X-Real-Ip']
else:
ip = request.remote_ip
return ip
def import_files_to_mongo():
"""Import unindexed files to the database"""
import os
import database
from tornado import gen, ioloop
from config import SETTINGS
@gen.engine
def do_insert(items):
for item in items:
arguments = yield gen.Task(db.images.insert, item)
result, error = arguments.args
if error:
raise error
ioloop.IOLoop.instance().stop()
images = os.listdir(SETTINGS['saved_files'])
images = filter(lambda x: not x.startswith('s') and not x.startswith('.'), images)
images.sort(key=lambda x: float(x[:-4]))
images_items = (
{
'src': image,
'date': from_unix(image[:-4]),
'unixtime': float(image[:-4]),
'ip': '',
'likes': database.images['likes']
}
for image in images
)
db = SETTINGS['db']
do_insert(images_items)
ioloop.IOLoop.instance().start()