User:Legoktm/toolforge library

From Wikitech
Jump to navigation Jump to search

toolforge is a simple Python 3 library to help with some common tasks that Toolforge users might encounter. Source code is published on Github. Patches welcome.


pip install toolforge.


Connect to databases

An example how to connect to a replicating database without needing to remember all the various options.

import toolforge
conn = toolforge.connect('enwiki')  # You can also use "enwiki_p"
# conn is a pymysql.connection object.
with conn.cursor() as cur:
    cur.execute(query)  # Or something....

Please keep the connection handling policy in mind – web tools should do this per request, not during application initialization.

Set proper user-agent

Set the default requests user-agent to one that complies with the Wikimedia User-Agent policy:

import requests
import toolforge

# Sets user-agent to:
# mycooltool (; python-requests/2.13.0

For cases where the default requests user-agent isn’t used, the function also returns the string to use instead:

import mwapi
import toolforge

user_agent = toolforge.set_user_agent('mycooltool')
session = mwapi.Session('',