-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmorguefile.py
More file actions
95 lines (69 loc) · 2.65 KB
/
morguefile.py
File metadata and controls
95 lines (69 loc) · 2.65 KB
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
# MORGUEFILE - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@trapdoor.be>
# Based on the MorgueFile API:
# http://box115.morguefile.com/wiki/index.php/Morguefile_api
from urllib.request import urlopen
from xml.dom.minidom import parseString
import os
class MorgueFileImage:
def __init__(self):
self.id = 0
self.category = ""
self.author = ""
self.name = ""
self.url = ""
self.date = ""
self.views = 0
self.downloads = 0
def download(self, path="", thumbnail=False):
""" Downloads the image to the given path folder.
If the path does not exist, attempts to create the path.
If thumbnail is True, downloads the image thumbnail.
Returns the filename at the given path.
The filename is composed of the author's name + image name.
"""
if path != "" and not os.path.isdir(path):
os.mkdir(path)
url = self.url
if thumbnail == False:
url = self.url.replace("thumbnails", "lowrez")
data = urlopen(url).read()
path = os.path.join(path, self.author + "_" + self.name)
f = open(path, "w")
f.write(data)
f.close()
return path
def search(q, max=100, _author=False):
""" Queries the MorgueFile API.
Returns a list of MorgueFileImage objects.
When _author is True, returns images that have q as author.
"""
q = q.replace(" ", "+")
arg = "terms"
if _author == True: arg = "author"
api = "http://morguefile.com/archive/archivexml.php"
api += "?" + arg + "=" + q + "&archive_max_image=" + str(max)
xml = urlopen(api).read()
dom = parseString(xml)
def _getdata(e, tag):
return e. getElementsByTagName(tag)[0].childNodes[0].data
images = []
for e in dom.getElementsByTagName("image"):
img = MorgueFileImage()
img.id = _getdata(e, "unique_id")
img.category = _getdata(e, "category")
img.author = _getdata(e, "author")
img.name = _getdata(e, "title")
img.url = _getdata(e, "photo_path")
img.date = _getdata(e, "date_added")
img.views = _getdata(e, "views")
img.downloads = _getdata(e, "downloads")
images.append(img)
return images
query = search
def search_by_author(author, max=100):
return search(author, max, _author=True)
query_by_author = search_by_author
def download(img, path="", thumbnail=False):
if isinstance(img, MorgueFileImage):
return img.download(path, thumbnail)