-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_and_add_meta.py
More file actions
95 lines (78 loc) · 2.34 KB
/
create_and_add_meta.py
File metadata and controls
95 lines (78 loc) · 2.34 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
"""
upload_file_directly.py
MediaWiki API Demos
Demo of `Upload` module: Sending post request to upload a file directly
MIT license
"""
import requests
from secrets import WIKI_BOT_USER, WIKI_BOT_PASS
# secrets.py file should have the user and password information
# I recommend using a bot instead of the full user
# Visit: https://www.mediawiki.org/wiki/Special:BotPasswords
# Bots can have restricted operability for security.
# Read more at https://en.wikipedia.org/wiki/Wikipedia:Bots
S = requests.Session()
URL = "https://test.wikipedia.org/w/api.php"
FILE_PATH = "test.jpg"
NEW_FN = f'test upload by.png'
# Step 1: Retrieve a login token
PARAMS_1 = {
"action": "query",
"meta": "tokens",
"type": "login",
"format": "json"
}
R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()
LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]
# Step 2: Send a post request to login. Use of main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
PARAMS_2 = {
"action": "login",
"lgname": WIKI_BOT_USER,
"lgpassword": WIKI_BOT_PASS,
"format": "json",
"lgtoken": LOGIN_TOKEN
}
R = S.post(URL, data=PARAMS_2)
# Step 3: Obtain a CSRF token
PARAMS_3 = {
"action": "query",
"meta":"tokens",
"format":"json"
}
R = S.get(url=URL, params=PARAMS_3)
DATA = R.json()
CSRF_TOKEN = DATA["query"]["tokens"]["csrftoken"]
# Step 4: Post request to upload a file directly
PARAMS_4 = {
"action": "upload",
"filename": NEW_FN,
"format": "json",
"token": CSRF_TOKEN,
"ignorewarnings": 1,
# Comment holds the page text. Should include any templates and sections.
# ==Section==
# ===Subsection===
# ====Sub-subsection====
# f" " or f""" """ strings require double {{ or }} to represent { or }.
# Single { and } are used for variables.
"comment": f"""==Description==
Test upload small screenshot 5.
==Summary==
===Metadata===
{{{{Information
|Description=(Image Description)
|Date=(Date of image creation)
|Source=(URL to Image)
|Author={WIKI_BOT_USER}
|Permission=(Enter your permissions)
}}}}"""
}
FILE = {'file':(NEW_FN, open(FILE_PATH, 'rb'), 'multipart/form-data')}
R = S.post(URL, files=FILE, data=PARAMS_4)
print("\n\n", R.text, "\n\n\n",)
DATA = R.json()
print(DATA)
S.close()