Page MenuHomec4science

tequila.py
No OneTemporary

File Metadata

Created
Sat, Apr 27, 12:57

tequila.py

# -*- coding: utf-8 -*-
'''
This code is adapted from the conde of Antoine Albertelli, found here:
https://github.com/antoinealb/python-tequila
'''
import getpass
import requests
from bs4 import BeautifulSoup
import logging
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
logging.getLogger('requests').setLevel(logging.WARNING)
__author__ = "Nicolas Richart"
__copyright__ = "Copyright (C) 2016, EPFL (Ecole Polytechnique Fédérale " \
"de Lausanne) - SCITAS (Scientific IT and Application " \
"Support) \n\n" \
"Copyright (c) 2013, Antoine Albertelli"
__credits__ = ["Antoine Albertelli", "Nicolas Richart"]
__license__ = "BSD"
__version__ = "0.1"
__maintainer__ = "Nicolas Richart"
__email__ = "nicolas.richart@epfl.ch"
class TequilaGet(object):
"""Get url that needs tequila authentiication"""
TEQUILA_LOGIN_POST = "https://tequila.epfl.ch/cgi-bin/tequila/login"
__session = None
class TequilaError(RuntimeError):
"""
Exception thrown in case of Tequila error.
"""
pass
def __init__(self, url, username, password=None, **kwargs):
"""
Explicitly login into the tequila service, this will create
a new tequila session.
:raise TequilaError:
"""
self.__session = requests.session()
resp = self.__session.get(url)
if resp.status_code != 200:
raise TequilaGet.TequilaError('Cannot access {0}'.format(url))
parsed_url = urlparse.urlsplit(resp.url)
dict_query = urlparse.parse_qs(parsed_url.query)
sesskey = dict_query['requestkey'][0]
if password is None:
password = getpass.getpass(
'Tequilla password of user {0}: '.format(username))
payload = dict()
payload["requestkey"] = sesskey
payload["username"] = username
payload["password"] = password
resp = self.__session.post(self.TEQUILA_LOGIN_POST,
verify=True, data=payload)
if resp.status_code != 200:
raise TequilaGet.TequilaError("Tequila didn't return a 200 code")
soup = BeautifulSoup(resp.text, 'html.parser')
error = soup.find('font', color='red', size='+1')
if error:
# Grab the tequila error if any
raise TequilaGet.TequilaError(error.string)
def get(self, url):
"""Get an url in a authenticated session"""
resp = self.__session.get(url)
if resp.status_code != 200:
raise TequilaGet.TequilaError()
return resp

Event Timeline