repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
kalbhor/MusicNow
|
musicnow/repair.py
|
get_lyrics_letssingit
|
python
|
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
|
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L76-L104
| null |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
get_lyrics_genius
|
python
|
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
|
Scrapes the lyrics from Genius.com
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L106-L130
| null |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
get_details_spotify
|
python
|
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
|
Tries finding metadata through Spotify
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L133-L166
|
[
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n",
"def songname(song_name):\n '''\n Improves file name by removing crap words\n '''\n try:\n song_name = splitext(song_name)[0]\n except IndexError:\n pass\n\n # Words to omit from song title for better results through spotify's API\n chars_filter = \"()[]{}-:_/=+\\\"\\'\"\n words_filter = ('official', 'lyrics', 'audio', 'remixed', 'remix', 'video',\n 'full', 'version', 'music', 'mp3', 'hd', 'hq', 'uploaded')\n\n # Replace characters to filter with spaces\n song_name = ''.join(map(lambda c: \" \" if c in chars_filter else c, song_name))\n\n # Remove crap words\n song_name = re.sub('|'.join(re.escape(key) for key in words_filter),\n \"\", song_name, flags=re.IGNORECASE)\n\n # Remove duplicate spaces\n song_name = re.sub(' +', ' ', song_name)\n return song_name.strip()\n",
"def log_indented(text='', newline=False, trailing_newline=False):\n log(' %s' % text, newline=newline, trailing_newline=trailing_newline)\n",
"def matching_details(song_name, song_title, artist):\n '''\n Provides a score out of 10 that determines the\n relevance of the search result\n '''\n\n match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()\n match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()\n\n if max(match_name,match_title) >= 0.55:\n return True, max(match_name,match_title)\n\n else:\n return False, (match_name + match_title) / 2\n",
"def get_lyrics_letssingit(song_name):\n '''\n Scrapes the lyrics of a song since spotify does not provide lyrics\n takes song title as arguement\n '''\n\n lyrics = \"\"\n url = \"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\" + \\\n quote(song_name.encode('utf-8'))\n html = urlopen(url).read()\n soup = BeautifulSoup(html, \"html.parser\")\n link = soup.find('a', {'class': 'high_profile'})\n\n try:\n link = link.get('href')\n link = urlopen(link).read()\n soup = BeautifulSoup(link, \"html.parser\")\n\n try:\n lyrics = soup.find('div', {'id': 'lyrics'}).text\n lyrics = lyrics[3:]\n\n except AttributeError:\n lyrics = \"\"\n\n except:\n lyrics = \"\"\n\n return lyrics\n",
"def get_lyrics_genius(song_title):\n '''\n Scrapes the lyrics from Genius.com\n '''\n base_url = \"http://api.genius.com\"\n headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}\n search_url = base_url + \"/search\"\n data = {'q': song_title}\n\n response = requests.get(search_url, data=data, headers=headers)\n json = response.json()\n song_api_path = json[\"response\"][\"hits\"][0][\"result\"][\"api_path\"]\n\n song_url = base_url + song_api_path\n response = requests.get(song_url, headers=headers)\n json = response.json()\n path = json[\"response\"][\"song\"][\"path\"]\n page_url = \"http://genius.com\" + path\n\n page = requests.get(page_url)\n soup = BeautifulSoup(page.text, \"html.parser\")\n div = soup.find('div',{'class': 'song_body-lyrics'})\n lyrics = div.find('p').getText()\n\n return lyrics\n"
] |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
get_details_letssingit
|
python
|
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
|
Gets the song details if song details not found through spotify
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L169-L227
|
[
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n",
"def songname(song_name):\n '''\n Improves file name by removing crap words\n '''\n try:\n song_name = splitext(song_name)[0]\n except IndexError:\n pass\n\n # Words to omit from song title for better results through spotify's API\n chars_filter = \"()[]{}-:_/=+\\\"\\'\"\n words_filter = ('official', 'lyrics', 'audio', 'remixed', 'remix', 'video',\n 'full', 'version', 'music', 'mp3', 'hd', 'hq', 'uploaded')\n\n # Replace characters to filter with spaces\n song_name = ''.join(map(lambda c: \" \" if c in chars_filter else c, song_name))\n\n # Remove crap words\n song_name = re.sub('|'.join(re.escape(key) for key in words_filter),\n \"\", song_name, flags=re.IGNORECASE)\n\n # Remove duplicate spaces\n song_name = re.sub(' +', ' ', song_name)\n return song_name.strip()\n",
"def matching_details(song_name, song_title, artist):\n '''\n Provides a score out of 10 that determines the\n relevance of the search result\n '''\n\n match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()\n match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()\n\n if max(match_name,match_title) >= 0.55:\n return True, max(match_name,match_title)\n\n else:\n return False, (match_name + match_title) / 2\n"
] |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
add_albumart
|
python
|
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
|
Adds the album art to the song
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L230-L258
|
[
"def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n",
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n"
] |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
add_details
|
python
|
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
|
Adds the details to song
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L261-L281
|
[
"def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n",
"def log_indented(text='', newline=False, trailing_newline=False):\n log(' %s' % text, newline=newline, trailing_newline=trailing_newline)\n"
] |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
fix_music
|
python
|
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
|
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L284-L330
|
[
"def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n",
"def setup():\n \"\"\"\n Gathers all configs\n \"\"\"\n\n global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR \n\n LOG_FILENAME = 'musicrepair_log.txt'\n LOG_LINE_SEPERATOR = '........................\\n'\n\n CONFIG = configparser.ConfigParser()\n config_path = realpath(__file__).replace(basename(__file__),'')\n config_path = config_path + 'config.ini'\n CONFIG.read(config_path)\n\n GENIUS_KEY = CONFIG['keys']['genius_key']\n",
"def img_search_bing(album):\n ''' Bing image search '''\n\n setup()\n\n album = album + \" Album Art\"\n\n api_key = \"Key\"\n endpoint = \"https://api.cognitive.microsoft.com/bing/v5.0/images/search\"\n links_dict = {}\n\n headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)}\n param = {'q': album, 'count': '1'}\n\n response = requests.get(endpoint, headers=headers, params=param)\n response = response.json()\n\n key = 0\n try:\n for i in response['value']:\n links_dict[str(key)] = str((i['contentUrl']))\n key = key + 1\n\n return links_dict[\"0\"]\n\n except KeyError:\n return None\n",
"def img_search_google(album):\n '''\n google image search\n '''\n\n album = album + \" Album Art\"\n url = (\"https://www.google.com/search?q=\" +\n quote(album.encode('utf-8')) + \"&source=lnms&tbm=isch\")\n header = {'User-Agent':\n '''Mozilla/5.0 (Windows NT 6.1; WOW64)\n AppleWebKit/537.36 (KHTML,like Gecko)\n Chrome/43.0.2357.134 Safari/537.36'''\n }\n\n\n\n soup = BeautifulSoup(urlopen(Request(url, headers=header)), \"html.parser\")\n\n albumart_div = soup.find(\"div\", {\"class\": \"rg_meta\"})\n albumart = json.loads(albumart_div.text)[\"ou\"]\n\n return albumart\n",
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n",
"def log_indented(text='', newline=False, trailing_newline=False):\n log(' %s' % text, newline=newline, trailing_newline=trailing_newline)\n",
"def log_success():\n text = 'Finished successfully'\n log('%s%s%s' % (Fore.GREEN, text, Fore.RESET))\n",
"def get_details_spotify(song_name):\n '''\n Tries finding metadata through Spotify\n '''\n\n song_name = improvename.songname(song_name)\n\n spotify = spotipy.Spotify()\n results = spotify.search(song_name, limit=1) # Find top result\n\n log.log_indented('* Finding metadata from Spotify.')\n\n try:\n album = (results['tracks']['items'][0]['album']\n ['name']) # Parse json dictionary\n artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])\n song_title = (results['tracks']['items'][0]['name'])\n try:\n log_indented(\"* Finding lyrics from Genius.com\")\n lyrics = get_lyrics_genius(song_title)\n except:\n log_error(\"* Could not find lyrics from Genius.com, trying something else\")\n lyrics = get_lyrics_letssingit(song_title)\n\n match_bool, score = matching_details(song_name, song_title, artist)\n if match_bool:\n return artist, album, song_title, lyrics, match_bool, score\n else:\n return None\n\n except IndexError:\n log.log_error(\n '* Could not find metadata from spotify, trying something else.', indented=True)\n return None\n",
"def get_details_letssingit(song_name):\n '''\n Gets the song details if song details not found through spotify\n '''\n\n song_name = improvename.songname(song_name)\n\n url = \"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\" + \\\n quote(song_name.encode('utf-8'))\n html = urlopen(url).read()\n soup = BeautifulSoup(html, \"html.parser\")\n link = soup.find('a', {'class': 'high_profile'})\n try:\n link = link.get('href')\n link = urlopen(link).read()\n\n soup = BeautifulSoup(link, \"html.parser\")\n\n album_div = soup.find('div', {'id': 'albums'})\n title_div = soup.find('div', {'id': 'content_artist'}).find('h1')\n\n try:\n lyrics = soup.find('div', {'id': 'lyrics'}).text\n lyrics = lyrics[3:]\n except AttributeError:\n lyrics = \"\"\n log.log_error(\"* Couldn't find lyrics\", indented=True)\n\n try:\n song_title = title_div.contents[0]\n song_title = song_title[1:-8]\n except AttributeError:\n log.log_error(\"* Couldn't reset song title\", indented=True)\n song_title = song_name\n\n try:\n artist = title_div.contents[1].getText()\n except AttributeError:\n log.log_error(\"* Couldn't find artist name\", indented=True)\n artist = \"Unknown\"\n\n try:\n album = album_div.find('a').contents[0]\n album = album[:-7]\n except AttributeError:\n log.log_error(\"* Couldn't find the album name\", indented=True)\n album = artist\n\n except AttributeError:\n log.log_error(\"* Couldn't find song details\", indented=True)\n\n album = song_name\n song_title = song_name\n artist = \"Unknown\"\n lyrics = \"\"\n\n match_bool, score = matching_details(song_name, song_title, artist)\n\n return artist, album, song_title, lyrics, match_bool, score\n",
"def add_albumart(albumart, song_title):\n '''\n Adds the album art to the song\n '''\n\n try:\n img = urlopen(albumart) # Gets album art from url\n\n except Exception:\n log.log_error(\"* Could not add album art\", indented=True)\n return None\n\n audio = EasyMP3(song_title, ID3=ID3)\n try:\n audio.add_tags()\n except _util.error:\n pass\n\n audio.tags.add(\n APIC(\n encoding=3, # UTF-8\n mime='image/png',\n type=3, # 3 is for album art\n desc='Cover',\n data=img.read() # Reads and adds album art\n )\n )\n audio.save()\n log.log(\"> Added album art\")\n",
"def add_details(file_name, title, artist, album, lyrics=\"\"):\n '''\n Adds the details to song\n '''\n\n tags = EasyMP3(file_name)\n tags[\"title\"] = title\n tags[\"artist\"] = artist\n tags[\"album\"] = album\n tags.save()\n\n tags = ID3(file_name)\n uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)\n tags[\"USLT::'eng'\"] = uslt_output\n\n tags.save(file_name)\n\n log.log(\"> Adding properties\")\n log.log_indented(\"[*] Title: %s\" % title)\n log.log_indented(\"[*] Artist: %s\" % artist)\n log.log_indented(\"[*] Album: %s \" % album)\n"
] |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/albumsearch.py
|
img_search_bing
|
python
|
def img_search_bing(album):
''' Bing image search '''
setup()
album = album + " Album Art"
api_key = "Key"
endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
links_dict = {}
headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)}
param = {'q': album, 'count': '1'}
response = requests.get(endpoint, headers=headers, params=param)
response = response.json()
key = 0
try:
for i in response['value']:
links_dict[str(key)] = str((i['contentUrl']))
key = key + 1
return links_dict["0"]
except KeyError:
return None
|
Bing image search
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/albumsearch.py#L42-L68
|
[
"def setup():\n \"\"\"\n Gathers all configs\n \"\"\"\n\n global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR \n\n LOG_FILENAME = 'musicrepair_log.txt'\n LOG_LINE_SEPERATOR = '........................\\n'\n\n CONFIG = configparser.ConfigParser()\n config_path = realpath(__file__).replace(basename(__file__),'')\n config_path = config_path + 'config.ini'\n CONFIG.read(config_path)\n\n BING_KEY = CONFIG['keys']['bing_key']\n"
] |
'''
Return Album Art url
'''
try:
from . import log
except:
import log
import requests
import json
from bs4 import BeautifulSoup
import six
from os import environ
from os.path import realpath, basename
if six.PY2:
from urllib2 import urlopen, Request
from urllib2 import quote
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen, Request
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
BING_KEY = CONFIG['keys']['bing_key']
def img_search_bing(album):
''' Bing image search '''
setup()
album = album + " Album Art"
api_key = "Key"
endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
links_dict = {}
headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)}
param = {'q': album, 'count': '1'}
response = requests.get(endpoint, headers=headers, params=param)
response = response.json()
key = 0
try:
for i in response['value']:
links_dict[str(key)] = str((i['contentUrl']))
key = key + 1
return links_dict["0"]
except KeyError:
return None
def img_search_google(album):
'''
google image search
'''
album = album + " Album Art"
url = ("https://www.google.com/search?q=" +
quote(album.encode('utf-8')) + "&source=lnms&tbm=isch")
header = {'User-Agent':
'''Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML,like Gecko)
Chrome/43.0.2357.134 Safari/537.36'''
}
soup = BeautifulSoup(urlopen(Request(url, headers=header)), "html.parser")
albumart_div = soup.find("div", {"class": "rg_meta"})
albumart = json.loads(albumart_div.text)["ou"]
return albumart
|
kalbhor/MusicNow
|
musicnow/albumsearch.py
|
img_search_google
|
python
|
def img_search_google(album):
'''
google image search
'''
album = album + " Album Art"
url = ("https://www.google.com/search?q=" +
quote(album.encode('utf-8')) + "&source=lnms&tbm=isch")
header = {'User-Agent':
'''Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML,like Gecko)
Chrome/43.0.2357.134 Safari/537.36'''
}
soup = BeautifulSoup(urlopen(Request(url, headers=header)), "html.parser")
albumart_div = soup.find("div", {"class": "rg_meta"})
albumart = json.loads(albumart_div.text)["ou"]
return albumart
|
google image search
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/albumsearch.py#L70-L91
| null |
'''
Return Album Art url
'''
try:
from . import log
except:
import log
import requests
import json
from bs4 import BeautifulSoup
import six
from os import environ
from os.path import realpath, basename
if six.PY2:
from urllib2 import urlopen, Request
from urllib2 import quote
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen, Request
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
BING_KEY = CONFIG['keys']['bing_key']
def img_search_bing(album):
''' Bing image search '''
setup()
album = album + " Album Art"
api_key = "Key"
endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
links_dict = {}
headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)}
param = {'q': album, 'count': '1'}
response = requests.get(endpoint, headers=headers, params=param)
response = response.json()
key = 0
try:
for i in response['value']:
links_dict[str(key)] = str((i['contentUrl']))
key = key + 1
return links_dict["0"]
except KeyError:
return None
def img_search_google(album):
'''
google image search
'''
album = album + " Album Art"
url = ("https://www.google.com/search?q=" +
quote(album.encode('utf-8')) + "&source=lnms&tbm=isch")
header = {'User-Agent':
'''Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML,like Gecko)
Chrome/43.0.2357.134 Safari/537.36'''
}
soup = BeautifulSoup(urlopen(Request(url, headers=header)), "html.parser")
albumart_div = soup.find("div", {"class": "rg_meta"})
albumart = json.loads(albumart_div.text)["ou"]
return albumart
|
kalbhor/MusicNow
|
musicnow/improvename.py
|
songname
|
python
|
def songname(song_name):
'''
Improves file name by removing crap words
'''
try:
song_name = splitext(song_name)[0]
except IndexError:
pass
# Words to omit from song title for better results through spotify's API
chars_filter = "()[]{}-:_/=+\"\'"
words_filter = ('official', 'lyrics', 'audio', 'remixed', 'remix', 'video',
'full', 'version', 'music', 'mp3', 'hd', 'hq', 'uploaded')
# Replace characters to filter with spaces
song_name = ''.join(map(lambda c: " " if c in chars_filter else c, song_name))
# Remove crap words
song_name = re.sub('|'.join(re.escape(key) for key in words_filter),
"", song_name, flags=re.IGNORECASE)
# Remove duplicate spaces
song_name = re.sub(' +', ' ', song_name)
return song_name.strip()
|
Improves file name by removing crap words
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/improvename.py#L5-L28
| null |
import re
from os.path import splitext
|
pavlov99/jsonapi
|
jsonapi/serializers.py
|
DatetimeDecimalEncoder.default
|
python
|
def default(self, o):
if isinstance(o, (datetime.datetime, datetime.date, datetime.time)):
return o.isoformat()
if isinstance(o, decimal.Decimal):
return float(o)
return json.JSONEncoder.default(self, o)
|
Encode JSON.
:return str: A JSON encoded string
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L17-L29
| null |
class DatetimeDecimalEncoder(json.JSONEncoder):
""" Encoder for datetime and decimal serialization.
Usage: json.dumps(object, cls=DatetimeDecimalEncoder)
NOTE: _iterencode does not work
"""
|
pavlov99/jsonapi
|
jsonapi/serializers.py
|
Serializer.dump_document
|
python
|
def dump_document(cls, instance, fields_own=None, fields_to_many=None):
if fields_own is not None:
fields_own = {f.name for f in fields_own}
else:
fields_own = {
f.name for f in instance._meta.fields
if f.rel is None and f.serialize
}
fields_own.add('id')
fields_own = (fields_own | set(cls.Meta.fieldnames_include))\
- set(cls.Meta.fieldnames_exclude)
document = {}
# Include own fields
for fieldname in fields_own:
field_serializer = getattr(
cls, "dump_document_{}".format(fieldname), None)
if field_serializer is not None:
value = field_serializer(instance)
else:
value = getattr(instance, fieldname)
try:
field = instance._meta.get_field(fieldname)
except models.fields.FieldDoesNotExist:
# Field is property, value already calculated
pass
else:
if isinstance(field, models.fields.files.FileField):
# TODO: Serializer depends on API here.
value = cls.Meta.api.base_url + value.url
elif isinstance(field, models.CommaSeparatedIntegerField):
value = [v for v in value]
document[fieldname] = value
# Include to-one fields. It does not require database calls
for field in instance._meta.fields:
fieldname = "{}_id".format(field.name)
# NOTE: check field is not related to parent model to exclude
# <class>_ptr fields. OneToOne relationship field.rel.multiple =
# False. Here make sure relationship is to parent model.
if field.rel and not field.rel.multiple \
and isinstance(instance, field.rel.to):
continue
if field.rel and fieldname not in cls.Meta.fieldnames_exclude:
document["links"] = document.get("links") or {}
document["links"][field.name] = getattr(instance, fieldname)
# Include to-many fields. It requires database calls. At this point we
# assume that model was prefetch_related with child objects, which would
# be included into 'linked' attribute. Here we need to add ids of linked
# objects. To avoid database calls, iterate over objects manually and
# get ids.
fields_to_many = fields_to_many or []
for field in fields_to_many:
document["links"] = document.get("links") or {}
document["links"][field.related_resource_name] = [
obj.id for obj in getattr(instance, field.name).all()]
return document
|
Get document for model_instance.
redefine dump rule for field x: def dump_document_x
:param django.db.models.Model instance: model instance
:param list<Field> or None fields: model_instance field to dump
:return dict: document
Related documents are not included to current one. In case of to-many
field serialization ensure that models_instance has been select_related
so, no database calls would be executed.
Method ensures that document has cls.Meta.fieldnames_include and does
not have cls.Meta.fieldnames_exclude
Steps:
1) fieldnames_include could be properties, but not related models.
Add them to fields_own.
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L66-L148
| null |
class Serializer(object):
""" Serializer class.
Serializer has methods dump_document and load_document to convert model
into document. Document is dictionary with following format:
{
"id" // The document SHOULD contain an "id" key.
}
* The "id" key in a document represents a unique identifier for the
underlying resource, scoped to its type. It MUST be a string which
SHOULD only contain alphanumeric characters, dashes and underscores.
In scenarios where uniquely identifying information between client and
server is unnecessary (e.g., read-only, transient entities), JSON API
allows for omitting the "id" key.
Serializer:
1) Check custom serializer for field in Resource
2) Try to use predefined serializers for fields
3) Try convert to string
"""
Meta = SerializerMeta
@classmethod
@classmethod
def dump_documents(cls, resource, model_instances, fields_own=None,
include_structure=None):
model_instances = list(model_instances)
model_info = resource.Meta.model_info
include_structure = include_structure or []
fields_to_many = set()
for include_object in include_structure:
f = include_object["field_path"][0]
if f.category == f.CATEGORIES.TO_MANY:
fields_to_many.add(f)
data = {
"data": [
cls.dump_document(
m,
fields_own=fields_own,
fields_to_many=fields_to_many
)
for m in model_instances
]
}
# TODO: move links generation to other method.
if model_info.fields_to_one or fields_to_many:
data["links"] = {}
for field in model_info.fields_to_one:
linkname = "{}.{}".format(resource.Meta.name_plural, field.name)
data["links"].update({
linkname: resource.Meta.api.api_url + "/" + field.name +
"/{" + linkname + "}"
})
if include_structure:
data["linked"] = []
for include_object in include_structure:
current_models = set(model_instances)
for field in include_object["field_path"]:
related_models = set()
for m in current_models:
if field.category == field.CATEGORIES.TO_MANY:
related_models |= set(getattr(m, field.name).all())
if field.category == field.CATEGORIES.TO_ONE:
related_model = getattr(m, field.name)
if related_model is not None:
related_models.add(related_model)
current_models = related_models
related_model_info = include_object["model_info"]
related_resource = include_object["resource"]
for rel_model in current_models:
linked_obj = related_resource.dump_document(
rel_model, related_model_info.fields_own
)
linked_obj["type"] = include_object["type"]
data["linked"].append(linked_obj)
return data
|
pavlov99/jsonapi
|
jsonapi/utils.py
|
_cached
|
python
|
def _cached(f):
attr_name = '_cached_' + f.__name__
def wrapper(obj, *args, **kwargs):
if not hasattr(obj, attr_name):
setattr(obj, attr_name, f(obj, *args, **kwargs))
return getattr(obj, attr_name)
return wrapper
|
Decorator that makes a method cached.
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/utils.py#L21-L30
| null |
""" JSON:API utils."""
class _classproperty(property):
""" Implement property behaviour for classes.
class A():
@_classproperty
@classmethod
def name(cls):
return cls.__name__
"""
def __get__(self, obj, type_):
return self.fget.__get__(None, type_)()
classproperty = lambda f: _classproperty(classmethod(f))
cached_property = lambda f: property(_cached(f))
cached_classproperty = lambda f: classproperty(_cached(f))
class Choices(object):
""" Choices."""
def __init__(self, *choices):
self._choices = []
self._choice_dict = {}
for choice in choices:
if isinstance(choice, (list, tuple)):
if len(choice) == 2:
choice = (choice[0], choice[1], choice[1])
elif len(choice) != 3:
raise ValueError(
"Choices can't handle a list/tuple of length {0}, only\
2 or 3".format(choice))
else:
choice = (choice, choice, choice)
self._choices.append((choice[0], choice[2]))
self._choice_dict[choice[1]] = choice[0]
def __getattr__(self, attname):
try:
return self._choice_dict[attname]
except KeyError:
raise AttributeError(attname)
def __iter__(self):
return iter(self._choices)
def __getitem__(self, index):
return self._choices[index]
def __delitem__(self, index):
del self._choices[index]
def __setitem__(self, index, value):
self._choices[index] = value
def __repr__(self):
return "{0}({1})".format(
self.__class__.__name__,
self._choices
)
def __len__(self):
return len(self._choices)
def __contains__(self, element):
return element in self._choice_dict.values()
|
pavlov99/jsonapi
|
jsonapi/model_inspector.py
|
ModelInspector._filter_child_model_fields
|
python
|
def _filter_child_model_fields(cls, fields):
indexes_to_remove = set([])
for index1, field1 in enumerate(fields):
for index2, field2 in enumerate(fields):
if index1 < index2 and index1 not in indexes_to_remove and\
index2 not in indexes_to_remove:
if issubclass(field1.related_model, field2.related_model):
indexes_to_remove.add(index1)
if issubclass(field2.related_model, field1.related_model):
indexes_to_remove.add(index2)
fields = [field for index, field in enumerate(fields)
if index not in indexes_to_remove]
return fields
|
Keep only related model fields.
Example: Inherited models: A -> B -> C
B has one-to-many relationship to BMany.
after inspection BMany would have links to B and C. Keep only B. Parent
model A could not be used (It would not be in fields)
:param list fields: model fields.
:return list fields: filtered fields.
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/model_inspector.py#L113-L139
| null |
class ModelInspector(object):
""" Inspect Django models."""
def inspect(self):
user_model = get_user_model()
self.models = {
model: ModelInfo(
get_model_name(model),
fields_own=self._get_fields_own(model),
fields_to_one=self._get_fields_self_foreign_key(model),
fields_to_many=self._get_fields_others_foreign_key(model) +
self._get_fields_self_many_to_many(model) +
self._get_fields_others_many_to_many(model),
is_user=(model is user_model or issubclass(model, user_model))
) for model in get_models()
}
for model, model_info in self.models.items():
if model_info.is_user:
model_info.auth_user_paths = ['']
else:
self._update_auth_user_paths_model(model)
model_info.field_resource_map = {
f.related_resource_name: f
for f in model_info.fields_to_one + model_info.fields_to_many
}
@classmethod
@classmethod
def _get_fields_own(cls, model):
fields = [
Field(
name=field.name,
related_model=None,
django_field=field,
category=Field.CATEGORIES.OWN
) for field in model._meta.fields
if field.rel is None and (field.serialize or field.name == 'id')
]
return fields
@classmethod
def _get_fields_self_foreign_key(cls, model):
fields = [
Field(
name=field.name,
related_model=field.rel.to,
django_field=field,
category=Field.CATEGORIES.TO_ONE
) for field in model._meta.fields
if field.rel and field.rel.multiple
]
return fields
@classmethod
def _get_fields_others_foreign_key(cls, model):
""" Get to-namy related field.
If related model has children, link current model only to related.
Child links make relationship complicated.
"""
fields = [
Field(
name=field.rel.related_name or "{}_set".format(
get_model_name(related_model)),
related_model=related_model,
django_field=field,
category=Field.CATEGORIES.TO_MANY
) for related_model in get_models()
if not related_model._meta.proxy
for field in related_model._meta.fields
if field.rel and field.rel.to is model._meta.concrete_model and
field.rel.multiple
]
fields = cls._filter_child_model_fields(fields)
return fields
@classmethod
def _get_fields_self_many_to_many(cls, model):
fields = [
Field(
name=field.name,
related_model=field.rel.to,
django_field=field,
category=Field.CATEGORIES.TO_MANY
) for field in model._meta.many_to_many
]
return fields
@classmethod
def _get_fields_others_many_to_many(cls, model):
fields = [
Field(
name=field.rel.related_name or "{}_set".format(
get_model_name(related_model)),
related_model=related_model,
django_field=field,
category=Field.CATEGORIES.TO_MANY
) for related_model in get_models()
if related_model is not model
for field in related_model._meta.many_to_many
if field.rel.to is model._meta.concrete_model
]
fields = cls._filter_child_model_fields(fields)
return fields
def _update_auth_user_paths_model(self, model):
# (field from previous model, related field of this model, model)
paths = [[(None, None, model)]]
while paths:
current_paths = paths
paths = []
for current_path in current_paths:
current_model = current_path[-1][-1]
current_model_info = self.models[current_model]
# NOTE: calculate used models links. Link is defined by model
# and field used.
used_links = set()
for node1, node2 in zip(current_path[:-1], current_path[1:]):
used_links.add((node1[2], node1[1]))
used_links.add((node2[2], node2[1]))
used_links.add((node1[2], node2[0]))
for field in current_model_info.relation_fields:
related_model = field.related_model
related_model_info = self.models[related_model]
for related_field in related_model_info.relation_fields:
related_related_model = related_field.related_model
if (related_related_model is current_model or
issubclass(current_model, related_related_model)) \
and (current_model, field) not in used_links \
and (related_model, related_field) not in \
used_links:
path = current_path + [
(field, related_field, related_model)]
if related_model_info.is_user:
self.models[model].auth_user_paths.append(
"__".join([
get_model_name(p[2]) for p in path[1:]
]))
else:
paths.append(path)
|
pavlov99/jsonapi
|
jsonapi/resource.py
|
get_concrete_model
|
python
|
def get_concrete_model(model):
if not(inspect.isclass(model) and issubclass(model, models.Model)):
model = get_model_by_name(model)
return model
|
Get model defined in Meta.
:param str or django.db.models.Model model:
:return: model or None
:rtype django.db.models.Model or None:
:raise ValueError: model is not found or abstract
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L67-L79
|
[
"def get_model_by_name(model_name):\n \"\"\" Get model by its name.\n\n :param str model_name: name of model.\n :return django.db.models.Model:\n\n Example:\n get_concrete_model_by_name('auth.User')\n django.contrib.auth.models.User\n\n \"\"\"\n if isinstance(model_name, six.string_types) and \\\n len(model_name.split('.')) == 2:\n app_name, model_name = model_name.split('.')\n\n if django.VERSION[:2] < (1, 8):\n model = models.get_model(app_name, model_name)\n else:\n from django.apps import apps\n model = apps.get_model(app_name, model_name)\n else:\n raise ValueError(\"{0} is not a Django model\".format(model_name))\n\n return model\n"
] |
""" Resource definition.
There are two tipes of resources:
* simple resources
* model resources
Simple resources require name Meta property to be defined.
Example:
class SimpleResource(Resource):
class Meta:
name = "simple_name"
Django model resources require model to be defined
Example:
class ModelResource(Resource):
class Meta:
model = "myapp.mymodel"
There are several optional Meta parameters:
* fieldnames_include = None
* fieldnames_exclude = None
* page_size = None
* allowed_methods = ('GET',)
Properties:
* name_plural
* is_model
* is_inherited
* is_auth_user
"""
from . import six
from django.core.paginator import Paginator
from django.db import models, transaction, IntegrityError
from django.forms import ModelForm, ValidationError
import inspect
import json
import logging
from .utils import classproperty
from .django_utils import get_model_name, get_model_by_name
from .serializers import Serializer
from .auth import Authenticator
from .request_parser import RequestParser
from .model_inspector import ModelInspector
from .exceptions import (
JSONAPIError,
JSONAPIForbiddenError,
JSONAPIFormSaveError,
JSONAPIFormValidationError,
JSONAPIIntegrityError,
JSONAPIInvalidRequestDataMissingError,
JSONAPIParseError,
JSONAPIResourceValidationError,
)
__all__ = 'Resource',
logger = logging.getLogger(__name__)
model_inspector = ModelInspector()
model_inspector.inspect()
def get_resource_name(meta):
""" Define resource name based on Meta information.
:param Resource.Meta meta: resource meta information
:return: name of resource
:rtype: str
:raises ValueError:
"""
if meta.name is None and not meta.is_model:
msg = "Either name or model for resource.Meta shoud be provided"
raise ValueError(msg)
name = meta.name or get_model_name(get_concrete_model(meta.model))
return name
def merge_metas(*metas):
""" Merge meta parameters.
next meta has priority over current, it will overwrite attributes.
:param class or None meta: class with properties.
:return class: merged meta.
"""
metadict = {}
for meta in metas:
metadict.update(meta.__dict__)
metadict = {k: v for k, v in metadict.items() if not k.startswith('__')}
return type('Meta', (object, ), metadict)
class ResourceMetaClass(type):
""" Metaclass for JSON:API resources.
.. versionadded:: 0.5.0
Meta.is_auth_user whether model is AUTH_USER or not
Meta.is_inherited whether model has parent or not.
Meta.is_model: whether resource based on model or not
NOTE: is_inherited is used for related fields queries. For fields it is only
parent model used (django.db.models.Model).
"""
def __new__(mcs, name, bases, attrs):
cls = super(ResourceMetaClass, mcs).__new__(mcs, name, bases, attrs)
metas = [getattr(base, 'Meta', None) for base in bases]
metas.append(cls.Meta)
cls.Meta = merge_metas(*metas)
# NOTE: Resource.Meta should be defined before metaclass returns
# Resource.
if name == "Resource":
return cls
cls.Meta.is_model = bool(getattr(cls.Meta, 'model', False))
cls.Meta.name = get_resource_name(cls.Meta)
if cls.Meta.is_model:
model = get_concrete_model(cls.Meta.model)
cls.Meta.model = model
if model._meta.abstract:
raise ValueError(
"Abstract model {} could not be resource".format(model))
cls.Meta.model_info = model_inspector.models[cls.Meta.model]
cls.Meta.default_form = cls.Meta.form or cls.get_form()
cls.Meta.description = cls.__doc__ or ""
return cls
@six.add_metaclass(ResourceMetaClass)
class Resource(Serializer, Authenticator):
""" Base JSON:API resource class."""
class Meta:
name = None
# fieldnames_include = None # NOTE: moved to Serializer.
# fieldnames_exclude = None
page_size = None
allowed_methods = 'GET',
form = None
@classproperty
def name_plural(cls):
return "{0}s".format(cls.name)
@classmethod
def get_queryset(cls, user=None, **kwargs):
""" Get objects queryset.
Method is used to generate objects queryset for resource operations.
It is aimed to:
* Filter objects based on user. Object could be in queryset only if
there is attribute-ForeignKey-ManyToMany path from current resource
to current auth_user.
* Select related objects (or prefetch them) based on requested
requested objects to include
NOTE: use user from parameters, it could be authenticated not with
session, so request.user might not work
"""
queryset = cls.Meta.model.objects
if cls.Meta.authenticators:
queryset = cls.update_user_queryset(queryset, user, **kwargs)
return queryset
@classmethod
def update_user_queryset(cls, queryset, user=None, **kwargs):
""" Update queryset based on given user.
.. versionadded:: 0.6.9
Method is used to control permissions during resource management.
"""
user_filter = models.Q()
for path in cls.Meta.model_info.auth_user_paths:
querydict = {path: user} if path else {"id": user.id}
user_filter = user_filter | models.Q(**querydict)
queryset = queryset.filter(user_filter)
return queryset
@classmethod
def get_filters(cls, filters):
""" Filter given queryset.
.. note:: Method is used to define custom filters.
Parameters
----------
filters : list
list of strings in form 'a=b' to apply to queryset
Returns
-------
dict
key is django filter expression, value is a filter value.
"""
result = dict()
for f in filters:
if not isinstance(f, six.string_types):
msg = "Value {} is not supported for filtering".format(f)
raise ValueError(msg)
result.update(dict([f.split('=', 1)]))
return result
@classmethod
def update_get_queryset(cls, queryset, **kwargs):
""" Update permission queryset for GET operations."""
return queryset
@classmethod
def update_post_queryset(cls, queryset, **kwargs):
""" Update permission queryset for POST operations."""
return queryset
@classmethod
def update_put_queryset(cls, queryset, **kwargs):
""" Update permission queryset for PUT operations."""
return queryset
@classmethod
def update_delete_queryset(cls, queryset, **kwargs):
""" Update permission queryset for delete operations."""
return queryset
@classmethod
def get_form(cls):
""" Create Partial Form based on given fields."""
if cls.Meta.form:
return cls.Meta.form
meta_attributes = {"model": cls.Meta.model, "fields": '__all__'}
Form = type('Form', (ModelForm,), {
"Meta": type('Meta', (object,), meta_attributes)
})
return Form
@classmethod
def get_partial_form(cls, Form, fields):
""" Get partial form based on original Form and fields set.
:param Form: django.forms.ModelForm
:param list fields: list of field names.
"""
if not fields:
return Form
if not set(fields) <= set(Form.base_fields.keys()):
# Set of requested fields is not subset of original form fields
# Django itself does not raise exception here.
fields = set(fields) & set(Form.base_fields.keys())
meta_attributes = dict(fields=list(fields))
# NOTE: if Form was created automatically, it's Meta is inherited from
# object already, double inheritance raises error. If form is general
# ModelForm created by user, it's Meta is not inherited from object and
# PartialForm creation raises error.
meta_bases = (Form.Meta,)
if not issubclass(Form.Meta, object):
meta_bases += (object,)
PartialForm = type('PartialForm', (Form,), {
"Meta": type('Meta', meta_bases, meta_attributes)
})
return PartialForm
@classmethod
def _get_include_structure(cls, include=None):
result = []
include = include or []
for include_path in include:
current_model = cls.Meta.model
field_path = []
for include_name in include_path.split('.'):
model_info = model_inspector.models[current_model]
field = model_info.field_resource_map[include_name]
field_path.append(field)
current_model = field.related_model
result.append({
"field_path": field_path,
"model_info": model_inspector.models[current_model],
"resource": cls.Meta.api.model_resource_map[current_model],
"type": field_path[-1].related_resource_name,
"query": "__".join([f.name for f in field_path])
})
return result
@classmethod
def get(cls, request=None, **kwargs):
""" Get resource http response.
:return str: resource
"""
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryargs = RequestParser.parse(request.GET)
# Filters
if 'ids' in kwargs:
queryset = queryset.filter(id__in=kwargs['ids'])
queryset = queryset.filter(**cls.get_filters(queryargs.filter))
# Distinct
if queryargs.distinct:
queryset = queryset.distinct(*queryargs.distinct)
# Sort
if queryargs.sort:
queryset = queryset.order_by(*queryargs.sort)
include = queryargs.include
include_structure = cls._get_include_structure(include)
# Update queryset based on include parameters.
for include_resource in include_structure:
field = include_resource['field_path'][-1]
related_query_type = 'select_related' \
if field.category == field.CATEGORIES.TO_ONE \
else 'prefetch_related'
queryset = getattr(queryset, related_query_type)(
include_resource['query'])
# Fields serialisation
# NOTE: currently filter only own fields
model_info = cls.Meta.model_info
fields_own = model_info.fields_own
if queryargs.fields:
fieldnames = queryargs.fields
fields_own = [f for f in fields_own if f.name in fieldnames]
objects = queryset.all()
meta = {}
if cls.Meta.page_size is not None:
paginator = Paginator(queryset, cls.Meta.page_size)
page = int(queryargs.page or 1)
meta["count"] = paginator.count
meta["num_pages"] = paginator.num_pages
meta["page_size"] = cls.Meta.page_size
meta["page"] = page
objects = paginator.page(page)
meta["page_next"] = objects.next_page_number() \
if objects.has_next() else None
meta["page_prev"] = objects.previous_page_number() \
if objects.has_previous() else None
response = cls.dump_documents(
cls,
objects,
fields_own=fields_own,
include_structure=include_structure
)
if meta:
response["meta"] = meta
return response
@classmethod
def extract_resource_items(cls, request):
""" Extract resources from django request.
:param: request django.HttpRequest
:return: (items, is_collection)
is_collection is True if items is list, False if object
items is list of items
"""
jdata = request.body.decode('utf8')
try:
data = json.loads(jdata)
except ValueError:
raise JSONAPIParseError(detail=jdata)
try:
items = data["data"]
except KeyError:
raise JSONAPIInvalidRequestDataMissingError()
is_collection = isinstance(items, list)
if not is_collection:
items = [items]
return (items, is_collection)
@classmethod
def clean_resources(cls, resources, request=None, **kwargs):
""" Clean resources before models management.
If models management requires resources, such as database calls or
external services communication, one may possible to clean resources
before it.
It is also possible to validate user permissions to do operation. Use
form validation if validation does not require user access and Resource
validation (this method) if it requires to access user object.
Parameters
----------
resources : list
List of dictionaries - serialized objects.
Returns
-------
resources : list
List of cleaned resources
Raises
------
django.forms.ValidationError in case of validation errors
"""
return resources
@classmethod
def _post_put(cls, request=None, **kwargs):
""" General method for post and put requests."""
items, is_collection = cls.extract_resource_items(request)
try:
items = cls.clean_resources(items, request=request, **kwargs)
except ValidationError as e:
raise JSONAPIResourceValidationError(detail=e.message)
if request.method == "PUT":
ids_set = set([int(_id) for _id in kwargs['ids']])
item_ids_set = {item["id"] for item in items}
if ids_set != item_ids_set:
msg = "ids set in url and request body are not matched"
raise JSONAPIError(detail=msg)
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryset = cls.update_put_queryset(queryset, **kwargs)
objects_map = queryset.in_bulk(kwargs["ids"])
if len(objects_map) < len(kwargs["ids"]):
msg = "You do not have access to objects {}".format(
list(ids_set - set(objects_map.keys()))
)
raise JSONAPIForbiddenError(detail=msg)
forms = []
attributes_include = []
fieldnames_to_many = []
for item in items:
if 'links' in item:
fieldnames_to_many = [
k for k, v in item['links'].items() if isinstance(v, list)]
item.update(item.pop('links'))
# Split resource data into original resource and attributes dict
# with keys from resource.Meta.fieldnames_include. Included fields
# could be of two types: 1) included in resource, but not model; 2)
# included in model (properties). In both cases fields could not be
# saved with form. Set those fields as attributes. In case 1)
# nothing would happed, because model does not have such attribute.
# In case 2) if model has setter for property, it would be set, if
# not, catch AttributeError and do nothing with it.
attribute_keys = set(item.keys()) & set(cls.Meta.fieldnames_include)
attributes_include.append({
k: v for k, v in item.items() if k in attribute_keys})
for key in attribute_keys:
del item[key]
# Prepare forms
if request.method == "POST":
Form = cls.get_form()
form = Form(item)
elif request.method == "PUT":
Form = cls.get_partial_form(cls.get_form(), item.keys())
instance = objects_map[item["id"]]
form = Form(item, instance=instance)
forms.append(form)
for index, form in enumerate(forms):
if not form.is_valid():
raise JSONAPIFormValidationError(
links=["/data/{}".format(index)],
paths=["/{}".format(attr) for attr in form.errors],
data=form.errors
)
data = []
try:
with transaction.atomic():
for form, instance_attributes in zip(forms, attributes_include):
instance = form.save()
# Set instance attributes: resource attributes or model
# properties with setters if exist.
for key, value in instance_attributes.items():
try:
setattr(instance, key, value)
except AttributeError:
# Do nothing if model's property does not have
# setter
pass
# save model only if there are attributes set.
if instance_attributes:
instance.save()
dumped_resource = cls.dump_document(instance)
for fieldname_to_many in fieldnames_to_many:
dumped_resource['links'][fieldname_to_many] = [
x.id for x in form.cleaned_data[fieldname_to_many]]
data.append(dumped_resource)
except IntegrityError as e:
raise JSONAPIIntegrityError(detail=str(e))
except Exception as e:
raise JSONAPIFormSaveError(detail=str(e))
if not is_collection:
data = data[0]
response = dict(data=data)
return response
@classmethod
def post(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def put(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def delete(cls, request=None, **kwargs):
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)\
.filter(id__in=kwargs['ids'])
if len(kwargs['ids']) > queryset.count():
raise JSONAPIForbiddenError()
queryset.delete()
return ""
|
pavlov99/jsonapi
|
jsonapi/resource.py
|
get_resource_name
|
python
|
def get_resource_name(meta):
if meta.name is None and not meta.is_model:
msg = "Either name or model for resource.Meta shoud be provided"
raise ValueError(msg)
name = meta.name or get_model_name(get_concrete_model(meta.model))
return name
|
Define resource name based on Meta information.
:param Resource.Meta meta: resource meta information
:return: name of resource
:rtype: str
:raises ValueError:
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L82-L96
|
[
"def get_model_name(model):\n \"\"\" Get model name for the field.\n\n Django 1.5 uses module_name, does not support model_name\n Django 1.6 uses module_name and model_name\n DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning\n\n \"\"\"\n opts = model._meta\n if django.VERSION[:2] < (1, 7):\n model_name = opts.module_name\n else:\n model_name = opts.model_name\n\n return model_name\n",
"def get_concrete_model(model):\n \"\"\" Get model defined in Meta.\n\n :param str or django.db.models.Model model:\n :return: model or None\n :rtype django.db.models.Model or None:\n :raise ValueError: model is not found or abstract\n\n \"\"\"\n if not(inspect.isclass(model) and issubclass(model, models.Model)):\n model = get_model_by_name(model)\n\n return model\n"
] |
""" Resource definition.
There are two tipes of resources:
* simple resources
* model resources
Simple resources require name Meta property to be defined.
Example:
class SimpleResource(Resource):
class Meta:
name = "simple_name"
Django model resources require model to be defined
Example:
class ModelResource(Resource):
class Meta:
model = "myapp.mymodel"
There are several optional Meta parameters:
* fieldnames_include = None
* fieldnames_exclude = None
* page_size = None
* allowed_methods = ('GET',)
Properties:
* name_plural
* is_model
* is_inherited
* is_auth_user
"""
from . import six
from django.core.paginator import Paginator
from django.db import models, transaction, IntegrityError
from django.forms import ModelForm, ValidationError
import inspect
import json
import logging
from .utils import classproperty
from .django_utils import get_model_name, get_model_by_name
from .serializers import Serializer
from .auth import Authenticator
from .request_parser import RequestParser
from .model_inspector import ModelInspector
from .exceptions import (
JSONAPIError,
JSONAPIForbiddenError,
JSONAPIFormSaveError,
JSONAPIFormValidationError,
JSONAPIIntegrityError,
JSONAPIInvalidRequestDataMissingError,
JSONAPIParseError,
JSONAPIResourceValidationError,
)
__all__ = 'Resource',
logger = logging.getLogger(__name__)
model_inspector = ModelInspector()
model_inspector.inspect()
def get_concrete_model(model):
""" Get model defined in Meta.
:param str or django.db.models.Model model:
:return: model or None
:rtype django.db.models.Model or None:
:raise ValueError: model is not found or abstract
"""
if not(inspect.isclass(model) and issubclass(model, models.Model)):
model = get_model_by_name(model)
return model
def merge_metas(*metas):
""" Merge meta parameters.
next meta has priority over current, it will overwrite attributes.
:param class or None meta: class with properties.
:return class: merged meta.
"""
metadict = {}
for meta in metas:
metadict.update(meta.__dict__)
metadict = {k: v for k, v in metadict.items() if not k.startswith('__')}
return type('Meta', (object, ), metadict)
class ResourceMetaClass(type):
""" Metaclass for JSON:API resources.
.. versionadded:: 0.5.0
Meta.is_auth_user whether model is AUTH_USER or not
Meta.is_inherited whether model has parent or not.
Meta.is_model: whether resource based on model or not
NOTE: is_inherited is used for related fields queries. For fields it is only
parent model used (django.db.models.Model).
"""
def __new__(mcs, name, bases, attrs):
cls = super(ResourceMetaClass, mcs).__new__(mcs, name, bases, attrs)
metas = [getattr(base, 'Meta', None) for base in bases]
metas.append(cls.Meta)
cls.Meta = merge_metas(*metas)
# NOTE: Resource.Meta should be defined before metaclass returns
# Resource.
if name == "Resource":
return cls
cls.Meta.is_model = bool(getattr(cls.Meta, 'model', False))
cls.Meta.name = get_resource_name(cls.Meta)
if cls.Meta.is_model:
model = get_concrete_model(cls.Meta.model)
cls.Meta.model = model
if model._meta.abstract:
raise ValueError(
"Abstract model {} could not be resource".format(model))
cls.Meta.model_info = model_inspector.models[cls.Meta.model]
cls.Meta.default_form = cls.Meta.form or cls.get_form()
cls.Meta.description = cls.__doc__ or ""
return cls
@six.add_metaclass(ResourceMetaClass)
class Resource(Serializer, Authenticator):
""" Base JSON:API resource class."""
class Meta:
name = None
# fieldnames_include = None # NOTE: moved to Serializer.
# fieldnames_exclude = None
page_size = None
allowed_methods = 'GET',
form = None
@classproperty
def name_plural(cls):
return "{0}s".format(cls.name)
@classmethod
def get_queryset(cls, user=None, **kwargs):
""" Get objects queryset.
Method is used to generate objects queryset for resource operations.
It is aimed to:
* Filter objects based on user. Object could be in queryset only if
there is attribute-ForeignKey-ManyToMany path from current resource
to current auth_user.
* Select related objects (or prefetch them) based on requested
requested objects to include
NOTE: use user from parameters, it could be authenticated not with
session, so request.user might not work
"""
queryset = cls.Meta.model.objects
if cls.Meta.authenticators:
queryset = cls.update_user_queryset(queryset, user, **kwargs)
return queryset
@classmethod
def update_user_queryset(cls, queryset, user=None, **kwargs):
""" Update queryset based on given user.
.. versionadded:: 0.6.9
Method is used to control permissions during resource management.
"""
user_filter = models.Q()
for path in cls.Meta.model_info.auth_user_paths:
querydict = {path: user} if path else {"id": user.id}
user_filter = user_filter | models.Q(**querydict)
queryset = queryset.filter(user_filter)
return queryset
@classmethod
def get_filters(cls, filters):
""" Filter given queryset.
.. note:: Method is used to define custom filters.
Parameters
----------
filters : list
list of strings in form 'a=b' to apply to queryset
Returns
-------
dict
key is django filter expression, value is a filter value.
"""
result = dict()
for f in filters:
if not isinstance(f, six.string_types):
msg = "Value {} is not supported for filtering".format(f)
raise ValueError(msg)
result.update(dict([f.split('=', 1)]))
return result
@classmethod
def update_get_queryset(cls, queryset, **kwargs):
""" Update permission queryset for GET operations."""
return queryset
@classmethod
def update_post_queryset(cls, queryset, **kwargs):
""" Update permission queryset for POST operations."""
return queryset
@classmethod
def update_put_queryset(cls, queryset, **kwargs):
""" Update permission queryset for PUT operations."""
return queryset
@classmethod
def update_delete_queryset(cls, queryset, **kwargs):
""" Update permission queryset for delete operations."""
return queryset
@classmethod
def get_form(cls):
""" Create Partial Form based on given fields."""
if cls.Meta.form:
return cls.Meta.form
meta_attributes = {"model": cls.Meta.model, "fields": '__all__'}
Form = type('Form', (ModelForm,), {
"Meta": type('Meta', (object,), meta_attributes)
})
return Form
@classmethod
def get_partial_form(cls, Form, fields):
""" Get partial form based on original Form and fields set.
:param Form: django.forms.ModelForm
:param list fields: list of field names.
"""
if not fields:
return Form
if not set(fields) <= set(Form.base_fields.keys()):
# Set of requested fields is not subset of original form fields
# Django itself does not raise exception here.
fields = set(fields) & set(Form.base_fields.keys())
meta_attributes = dict(fields=list(fields))
# NOTE: if Form was created automatically, it's Meta is inherited from
# object already, double inheritance raises error. If form is general
# ModelForm created by user, it's Meta is not inherited from object and
# PartialForm creation raises error.
meta_bases = (Form.Meta,)
if not issubclass(Form.Meta, object):
meta_bases += (object,)
PartialForm = type('PartialForm', (Form,), {
"Meta": type('Meta', meta_bases, meta_attributes)
})
return PartialForm
@classmethod
def _get_include_structure(cls, include=None):
result = []
include = include or []
for include_path in include:
current_model = cls.Meta.model
field_path = []
for include_name in include_path.split('.'):
model_info = model_inspector.models[current_model]
field = model_info.field_resource_map[include_name]
field_path.append(field)
current_model = field.related_model
result.append({
"field_path": field_path,
"model_info": model_inspector.models[current_model],
"resource": cls.Meta.api.model_resource_map[current_model],
"type": field_path[-1].related_resource_name,
"query": "__".join([f.name for f in field_path])
})
return result
@classmethod
def get(cls, request=None, **kwargs):
""" Get resource http response.
:return str: resource
"""
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryargs = RequestParser.parse(request.GET)
# Filters
if 'ids' in kwargs:
queryset = queryset.filter(id__in=kwargs['ids'])
queryset = queryset.filter(**cls.get_filters(queryargs.filter))
# Distinct
if queryargs.distinct:
queryset = queryset.distinct(*queryargs.distinct)
# Sort
if queryargs.sort:
queryset = queryset.order_by(*queryargs.sort)
include = queryargs.include
include_structure = cls._get_include_structure(include)
# Update queryset based on include parameters.
for include_resource in include_structure:
field = include_resource['field_path'][-1]
related_query_type = 'select_related' \
if field.category == field.CATEGORIES.TO_ONE \
else 'prefetch_related'
queryset = getattr(queryset, related_query_type)(
include_resource['query'])
# Fields serialisation
# NOTE: currently filter only own fields
model_info = cls.Meta.model_info
fields_own = model_info.fields_own
if queryargs.fields:
fieldnames = queryargs.fields
fields_own = [f for f in fields_own if f.name in fieldnames]
objects = queryset.all()
meta = {}
if cls.Meta.page_size is not None:
paginator = Paginator(queryset, cls.Meta.page_size)
page = int(queryargs.page or 1)
meta["count"] = paginator.count
meta["num_pages"] = paginator.num_pages
meta["page_size"] = cls.Meta.page_size
meta["page"] = page
objects = paginator.page(page)
meta["page_next"] = objects.next_page_number() \
if objects.has_next() else None
meta["page_prev"] = objects.previous_page_number() \
if objects.has_previous() else None
response = cls.dump_documents(
cls,
objects,
fields_own=fields_own,
include_structure=include_structure
)
if meta:
response["meta"] = meta
return response
@classmethod
def extract_resource_items(cls, request):
""" Extract resources from django request.
:param: request django.HttpRequest
:return: (items, is_collection)
is_collection is True if items is list, False if object
items is list of items
"""
jdata = request.body.decode('utf8')
try:
data = json.loads(jdata)
except ValueError:
raise JSONAPIParseError(detail=jdata)
try:
items = data["data"]
except KeyError:
raise JSONAPIInvalidRequestDataMissingError()
is_collection = isinstance(items, list)
if not is_collection:
items = [items]
return (items, is_collection)
@classmethod
def clean_resources(cls, resources, request=None, **kwargs):
""" Clean resources before models management.
If models management requires resources, such as database calls or
external services communication, one may possible to clean resources
before it.
It is also possible to validate user permissions to do operation. Use
form validation if validation does not require user access and Resource
validation (this method) if it requires to access user object.
Parameters
----------
resources : list
List of dictionaries - serialized objects.
Returns
-------
resources : list
List of cleaned resources
Raises
------
django.forms.ValidationError in case of validation errors
"""
return resources
@classmethod
def _post_put(cls, request=None, **kwargs):
""" General method for post and put requests."""
items, is_collection = cls.extract_resource_items(request)
try:
items = cls.clean_resources(items, request=request, **kwargs)
except ValidationError as e:
raise JSONAPIResourceValidationError(detail=e.message)
if request.method == "PUT":
ids_set = set([int(_id) for _id in kwargs['ids']])
item_ids_set = {item["id"] for item in items}
if ids_set != item_ids_set:
msg = "ids set in url and request body are not matched"
raise JSONAPIError(detail=msg)
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryset = cls.update_put_queryset(queryset, **kwargs)
objects_map = queryset.in_bulk(kwargs["ids"])
if len(objects_map) < len(kwargs["ids"]):
msg = "You do not have access to objects {}".format(
list(ids_set - set(objects_map.keys()))
)
raise JSONAPIForbiddenError(detail=msg)
forms = []
attributes_include = []
fieldnames_to_many = []
for item in items:
if 'links' in item:
fieldnames_to_many = [
k for k, v in item['links'].items() if isinstance(v, list)]
item.update(item.pop('links'))
# Split resource data into original resource and attributes dict
# with keys from resource.Meta.fieldnames_include. Included fields
# could be of two types: 1) included in resource, but not model; 2)
# included in model (properties). In both cases fields could not be
# saved with form. Set those fields as attributes. In case 1)
# nothing would happed, because model does not have such attribute.
# In case 2) if model has setter for property, it would be set, if
# not, catch AttributeError and do nothing with it.
attribute_keys = set(item.keys()) & set(cls.Meta.fieldnames_include)
attributes_include.append({
k: v for k, v in item.items() if k in attribute_keys})
for key in attribute_keys:
del item[key]
# Prepare forms
if request.method == "POST":
Form = cls.get_form()
form = Form(item)
elif request.method == "PUT":
Form = cls.get_partial_form(cls.get_form(), item.keys())
instance = objects_map[item["id"]]
form = Form(item, instance=instance)
forms.append(form)
for index, form in enumerate(forms):
if not form.is_valid():
raise JSONAPIFormValidationError(
links=["/data/{}".format(index)],
paths=["/{}".format(attr) for attr in form.errors],
data=form.errors
)
data = []
try:
with transaction.atomic():
for form, instance_attributes in zip(forms, attributes_include):
instance = form.save()
# Set instance attributes: resource attributes or model
# properties with setters if exist.
for key, value in instance_attributes.items():
try:
setattr(instance, key, value)
except AttributeError:
# Do nothing if model's property does not have
# setter
pass
# save model only if there are attributes set.
if instance_attributes:
instance.save()
dumped_resource = cls.dump_document(instance)
for fieldname_to_many in fieldnames_to_many:
dumped_resource['links'][fieldname_to_many] = [
x.id for x in form.cleaned_data[fieldname_to_many]]
data.append(dumped_resource)
except IntegrityError as e:
raise JSONAPIIntegrityError(detail=str(e))
except Exception as e:
raise JSONAPIFormSaveError(detail=str(e))
if not is_collection:
data = data[0]
response = dict(data=data)
return response
@classmethod
def post(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def put(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def delete(cls, request=None, **kwargs):
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)\
.filter(id__in=kwargs['ids'])
if len(kwargs['ids']) > queryset.count():
raise JSONAPIForbiddenError()
queryset.delete()
return ""
|
pavlov99/jsonapi
|
jsonapi/resource.py
|
merge_metas
|
python
|
def merge_metas(*metas):
metadict = {}
for meta in metas:
metadict.update(meta.__dict__)
metadict = {k: v for k, v in metadict.items() if not k.startswith('__')}
return type('Meta', (object, ), metadict)
|
Merge meta parameters.
next meta has priority over current, it will overwrite attributes.
:param class or None meta: class with properties.
:return class: merged meta.
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L99-L113
| null |
""" Resource definition.
There are two tipes of resources:
* simple resources
* model resources
Simple resources require name Meta property to be defined.
Example:
class SimpleResource(Resource):
class Meta:
name = "simple_name"
Django model resources require model to be defined
Example:
class ModelResource(Resource):
class Meta:
model = "myapp.mymodel"
There are several optional Meta parameters:
* fieldnames_include = None
* fieldnames_exclude = None
* page_size = None
* allowed_methods = ('GET',)
Properties:
* name_plural
* is_model
* is_inherited
* is_auth_user
"""
from . import six
from django.core.paginator import Paginator
from django.db import models, transaction, IntegrityError
from django.forms import ModelForm, ValidationError
import inspect
import json
import logging
from .utils import classproperty
from .django_utils import get_model_name, get_model_by_name
from .serializers import Serializer
from .auth import Authenticator
from .request_parser import RequestParser
from .model_inspector import ModelInspector
from .exceptions import (
JSONAPIError,
JSONAPIForbiddenError,
JSONAPIFormSaveError,
JSONAPIFormValidationError,
JSONAPIIntegrityError,
JSONAPIInvalidRequestDataMissingError,
JSONAPIParseError,
JSONAPIResourceValidationError,
)
__all__ = 'Resource',
logger = logging.getLogger(__name__)
model_inspector = ModelInspector()
model_inspector.inspect()
def get_concrete_model(model):
""" Get model defined in Meta.
:param str or django.db.models.Model model:
:return: model or None
:rtype django.db.models.Model or None:
:raise ValueError: model is not found or abstract
"""
if not(inspect.isclass(model) and issubclass(model, models.Model)):
model = get_model_by_name(model)
return model
def get_resource_name(meta):
""" Define resource name based on Meta information.
:param Resource.Meta meta: resource meta information
:return: name of resource
:rtype: str
:raises ValueError:
"""
if meta.name is None and not meta.is_model:
msg = "Either name or model for resource.Meta shoud be provided"
raise ValueError(msg)
name = meta.name or get_model_name(get_concrete_model(meta.model))
return name
class ResourceMetaClass(type):
""" Metaclass for JSON:API resources.
.. versionadded:: 0.5.0
Meta.is_auth_user whether model is AUTH_USER or not
Meta.is_inherited whether model has parent or not.
Meta.is_model: whether resource based on model or not
NOTE: is_inherited is used for related fields queries. For fields it is only
parent model used (django.db.models.Model).
"""
def __new__(mcs, name, bases, attrs):
cls = super(ResourceMetaClass, mcs).__new__(mcs, name, bases, attrs)
metas = [getattr(base, 'Meta', None) for base in bases]
metas.append(cls.Meta)
cls.Meta = merge_metas(*metas)
# NOTE: Resource.Meta should be defined before metaclass returns
# Resource.
if name == "Resource":
return cls
cls.Meta.is_model = bool(getattr(cls.Meta, 'model', False))
cls.Meta.name = get_resource_name(cls.Meta)
if cls.Meta.is_model:
model = get_concrete_model(cls.Meta.model)
cls.Meta.model = model
if model._meta.abstract:
raise ValueError(
"Abstract model {} could not be resource".format(model))
cls.Meta.model_info = model_inspector.models[cls.Meta.model]
cls.Meta.default_form = cls.Meta.form or cls.get_form()
cls.Meta.description = cls.__doc__ or ""
return cls
@six.add_metaclass(ResourceMetaClass)
class Resource(Serializer, Authenticator):
""" Base JSON:API resource class."""
class Meta:
name = None
# fieldnames_include = None # NOTE: moved to Serializer.
# fieldnames_exclude = None
page_size = None
allowed_methods = 'GET',
form = None
@classproperty
def name_plural(cls):
return "{0}s".format(cls.name)
@classmethod
def get_queryset(cls, user=None, **kwargs):
""" Get objects queryset.
Method is used to generate objects queryset for resource operations.
It is aimed to:
* Filter objects based on user. Object could be in queryset only if
there is attribute-ForeignKey-ManyToMany path from current resource
to current auth_user.
* Select related objects (or prefetch them) based on requested
requested objects to include
NOTE: use user from parameters, it could be authenticated not with
session, so request.user might not work
"""
queryset = cls.Meta.model.objects
if cls.Meta.authenticators:
queryset = cls.update_user_queryset(queryset, user, **kwargs)
return queryset
@classmethod
def update_user_queryset(cls, queryset, user=None, **kwargs):
""" Update queryset based on given user.
.. versionadded:: 0.6.9
Method is used to control permissions during resource management.
"""
user_filter = models.Q()
for path in cls.Meta.model_info.auth_user_paths:
querydict = {path: user} if path else {"id": user.id}
user_filter = user_filter | models.Q(**querydict)
queryset = queryset.filter(user_filter)
return queryset
@classmethod
def get_filters(cls, filters):
""" Filter given queryset.
.. note:: Method is used to define custom filters.
Parameters
----------
filters : list
list of strings in form 'a=b' to apply to queryset
Returns
-------
dict
key is django filter expression, value is a filter value.
"""
result = dict()
for f in filters:
if not isinstance(f, six.string_types):
msg = "Value {} is not supported for filtering".format(f)
raise ValueError(msg)
result.update(dict([f.split('=', 1)]))
return result
@classmethod
def update_get_queryset(cls, queryset, **kwargs):
""" Update permission queryset for GET operations."""
return queryset
@classmethod
def update_post_queryset(cls, queryset, **kwargs):
""" Update permission queryset for POST operations."""
return queryset
@classmethod
def update_put_queryset(cls, queryset, **kwargs):
""" Update permission queryset for PUT operations."""
return queryset
@classmethod
def update_delete_queryset(cls, queryset, **kwargs):
""" Update permission queryset for delete operations."""
return queryset
@classmethod
def get_form(cls):
""" Create Partial Form based on given fields."""
if cls.Meta.form:
return cls.Meta.form
meta_attributes = {"model": cls.Meta.model, "fields": '__all__'}
Form = type('Form', (ModelForm,), {
"Meta": type('Meta', (object,), meta_attributes)
})
return Form
@classmethod
def get_partial_form(cls, Form, fields):
""" Get partial form based on original Form and fields set.
:param Form: django.forms.ModelForm
:param list fields: list of field names.
"""
if not fields:
return Form
if not set(fields) <= set(Form.base_fields.keys()):
# Set of requested fields is not subset of original form fields
# Django itself does not raise exception here.
fields = set(fields) & set(Form.base_fields.keys())
meta_attributes = dict(fields=list(fields))
# NOTE: if Form was created automatically, it's Meta is inherited from
# object already, double inheritance raises error. If form is general
# ModelForm created by user, it's Meta is not inherited from object and
# PartialForm creation raises error.
meta_bases = (Form.Meta,)
if not issubclass(Form.Meta, object):
meta_bases += (object,)
PartialForm = type('PartialForm', (Form,), {
"Meta": type('Meta', meta_bases, meta_attributes)
})
return PartialForm
@classmethod
def _get_include_structure(cls, include=None):
result = []
include = include or []
for include_path in include:
current_model = cls.Meta.model
field_path = []
for include_name in include_path.split('.'):
model_info = model_inspector.models[current_model]
field = model_info.field_resource_map[include_name]
field_path.append(field)
current_model = field.related_model
result.append({
"field_path": field_path,
"model_info": model_inspector.models[current_model],
"resource": cls.Meta.api.model_resource_map[current_model],
"type": field_path[-1].related_resource_name,
"query": "__".join([f.name for f in field_path])
})
return result
@classmethod
def get(cls, request=None, **kwargs):
""" Get resource http response.
:return str: resource
"""
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryargs = RequestParser.parse(request.GET)
# Filters
if 'ids' in kwargs:
queryset = queryset.filter(id__in=kwargs['ids'])
queryset = queryset.filter(**cls.get_filters(queryargs.filter))
# Distinct
if queryargs.distinct:
queryset = queryset.distinct(*queryargs.distinct)
# Sort
if queryargs.sort:
queryset = queryset.order_by(*queryargs.sort)
include = queryargs.include
include_structure = cls._get_include_structure(include)
# Update queryset based on include parameters.
for include_resource in include_structure:
field = include_resource['field_path'][-1]
related_query_type = 'select_related' \
if field.category == field.CATEGORIES.TO_ONE \
else 'prefetch_related'
queryset = getattr(queryset, related_query_type)(
include_resource['query'])
# Fields serialisation
# NOTE: currently filter only own fields
model_info = cls.Meta.model_info
fields_own = model_info.fields_own
if queryargs.fields:
fieldnames = queryargs.fields
fields_own = [f for f in fields_own if f.name in fieldnames]
objects = queryset.all()
meta = {}
if cls.Meta.page_size is not None:
paginator = Paginator(queryset, cls.Meta.page_size)
page = int(queryargs.page or 1)
meta["count"] = paginator.count
meta["num_pages"] = paginator.num_pages
meta["page_size"] = cls.Meta.page_size
meta["page"] = page
objects = paginator.page(page)
meta["page_next"] = objects.next_page_number() \
if objects.has_next() else None
meta["page_prev"] = objects.previous_page_number() \
if objects.has_previous() else None
response = cls.dump_documents(
cls,
objects,
fields_own=fields_own,
include_structure=include_structure
)
if meta:
response["meta"] = meta
return response
@classmethod
def extract_resource_items(cls, request):
""" Extract resources from django request.
:param: request django.HttpRequest
:return: (items, is_collection)
is_collection is True if items is list, False if object
items is list of items
"""
jdata = request.body.decode('utf8')
try:
data = json.loads(jdata)
except ValueError:
raise JSONAPIParseError(detail=jdata)
try:
items = data["data"]
except KeyError:
raise JSONAPIInvalidRequestDataMissingError()
is_collection = isinstance(items, list)
if not is_collection:
items = [items]
return (items, is_collection)
@classmethod
def clean_resources(cls, resources, request=None, **kwargs):
""" Clean resources before models management.
If models management requires resources, such as database calls or
external services communication, one may possible to clean resources
before it.
It is also possible to validate user permissions to do operation. Use
form validation if validation does not require user access and Resource
validation (this method) if it requires to access user object.
Parameters
----------
resources : list
List of dictionaries - serialized objects.
Returns
-------
resources : list
List of cleaned resources
Raises
------
django.forms.ValidationError in case of validation errors
"""
return resources
@classmethod
def _post_put(cls, request=None, **kwargs):
""" General method for post and put requests."""
items, is_collection = cls.extract_resource_items(request)
try:
items = cls.clean_resources(items, request=request, **kwargs)
except ValidationError as e:
raise JSONAPIResourceValidationError(detail=e.message)
if request.method == "PUT":
ids_set = set([int(_id) for _id in kwargs['ids']])
item_ids_set = {item["id"] for item in items}
if ids_set != item_ids_set:
msg = "ids set in url and request body are not matched"
raise JSONAPIError(detail=msg)
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)
queryset = cls.update_put_queryset(queryset, **kwargs)
objects_map = queryset.in_bulk(kwargs["ids"])
if len(objects_map) < len(kwargs["ids"]):
msg = "You do not have access to objects {}".format(
list(ids_set - set(objects_map.keys()))
)
raise JSONAPIForbiddenError(detail=msg)
forms = []
attributes_include = []
fieldnames_to_many = []
for item in items:
if 'links' in item:
fieldnames_to_many = [
k for k, v in item['links'].items() if isinstance(v, list)]
item.update(item.pop('links'))
# Split resource data into original resource and attributes dict
# with keys from resource.Meta.fieldnames_include. Included fields
# could be of two types: 1) included in resource, but not model; 2)
# included in model (properties). In both cases fields could not be
# saved with form. Set those fields as attributes. In case 1)
# nothing would happed, because model does not have such attribute.
# In case 2) if model has setter for property, it would be set, if
# not, catch AttributeError and do nothing with it.
attribute_keys = set(item.keys()) & set(cls.Meta.fieldnames_include)
attributes_include.append({
k: v for k, v in item.items() if k in attribute_keys})
for key in attribute_keys:
del item[key]
# Prepare forms
if request.method == "POST":
Form = cls.get_form()
form = Form(item)
elif request.method == "PUT":
Form = cls.get_partial_form(cls.get_form(), item.keys())
instance = objects_map[item["id"]]
form = Form(item, instance=instance)
forms.append(form)
for index, form in enumerate(forms):
if not form.is_valid():
raise JSONAPIFormValidationError(
links=["/data/{}".format(index)],
paths=["/{}".format(attr) for attr in form.errors],
data=form.errors
)
data = []
try:
with transaction.atomic():
for form, instance_attributes in zip(forms, attributes_include):
instance = form.save()
# Set instance attributes: resource attributes or model
# properties with setters if exist.
for key, value in instance_attributes.items():
try:
setattr(instance, key, value)
except AttributeError:
# Do nothing if model's property does not have
# setter
pass
# save model only if there are attributes set.
if instance_attributes:
instance.save()
dumped_resource = cls.dump_document(instance)
for fieldname_to_many in fieldnames_to_many:
dumped_resource['links'][fieldname_to_many] = [
x.id for x in form.cleaned_data[fieldname_to_many]]
data.append(dumped_resource)
except IntegrityError as e:
raise JSONAPIIntegrityError(detail=str(e))
except Exception as e:
raise JSONAPIFormSaveError(detail=str(e))
if not is_collection:
data = data[0]
response = dict(data=data)
return response
@classmethod
def post(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def put(cls, request=None, **kwargs):
return cls._post_put(request=request, **kwargs)
@classmethod
def delete(cls, request=None, **kwargs):
user = cls.authenticate(request)
queryset = cls.get_queryset(user=user, **kwargs)\
.filter(id__in=kwargs['ids'])
if len(kwargs['ids']) > queryset.count():
raise JSONAPIForbiddenError()
queryset.delete()
return ""
|
pavlov99/jsonapi
|
jsonapi/django_utils.py
|
get_model_by_name
|
python
|
def get_model_by_name(model_name):
if isinstance(model_name, six.string_types) and \
len(model_name.split('.')) == 2:
app_name, model_name = model_name.split('.')
if django.VERSION[:2] < (1, 8):
model = models.get_model(app_name, model_name)
else:
from django.apps import apps
model = apps.get_model(app_name, model_name)
else:
raise ValueError("{0} is not a Django model".format(model_name))
return model
|
Get model by its name.
:param str model_name: name of model.
:return django.db.models.Model:
Example:
get_concrete_model_by_name('auth.User')
django.contrib.auth.models.User
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L12-L35
| null |
""" Django specific utils.
Utils are used to work with different django versions.
"""
import django
from django.db import models
from django.http import QueryDict
from . import six
def get_model_name(model):
""" Get model name for the field.
Django 1.5 uses module_name, does not support model_name
Django 1.6 uses module_name and model_name
DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
"""
opts = model._meta
if django.VERSION[:2] < (1, 7):
model_name = opts.module_name
else:
model_name = opts.model_name
return model_name
def clear_app_cache(app_name):
""" Clear django cache for models.
:param str ap_name: name of application to clear model cache
"""
loading_cache = django.db.models.loading.cache
if django.VERSION[:2] < (1, 7):
loading_cache.app_models[app_name].clear()
else:
loading_cache.all_models[app_name].clear()
def get_querydict(query):
if six.PY2:
return dict(QueryDict(query).iterlists())
else:
return dict(QueryDict(query).lists())
def get_models():
if django.VERSION[:2] < (1, 8):
return models.get_models()
else:
from django.apps import apps
return apps.get_models()
|
pavlov99/jsonapi
|
jsonapi/django_utils.py
|
get_model_name
|
python
|
def get_model_name(model):
opts = model._meta
if django.VERSION[:2] < (1, 7):
model_name = opts.module_name
else:
model_name = opts.model_name
return model_name
|
Get model name for the field.
Django 1.5 uses module_name, does not support model_name
Django 1.6 uses module_name and model_name
DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L38-L52
| null |
""" Django specific utils.
Utils are used to work with different django versions.
"""
import django
from django.db import models
from django.http import QueryDict
from . import six
def get_model_by_name(model_name):
""" Get model by its name.
:param str model_name: name of model.
:return django.db.models.Model:
Example:
get_concrete_model_by_name('auth.User')
django.contrib.auth.models.User
"""
if isinstance(model_name, six.string_types) and \
len(model_name.split('.')) == 2:
app_name, model_name = model_name.split('.')
if django.VERSION[:2] < (1, 8):
model = models.get_model(app_name, model_name)
else:
from django.apps import apps
model = apps.get_model(app_name, model_name)
else:
raise ValueError("{0} is not a Django model".format(model_name))
return model
def clear_app_cache(app_name):
""" Clear django cache for models.
:param str ap_name: name of application to clear model cache
"""
loading_cache = django.db.models.loading.cache
if django.VERSION[:2] < (1, 7):
loading_cache.app_models[app_name].clear()
else:
loading_cache.all_models[app_name].clear()
def get_querydict(query):
if six.PY2:
return dict(QueryDict(query).iterlists())
else:
return dict(QueryDict(query).lists())
def get_models():
if django.VERSION[:2] < (1, 8):
return models.get_models()
else:
from django.apps import apps
return apps.get_models()
|
pavlov99/jsonapi
|
jsonapi/django_utils.py
|
clear_app_cache
|
python
|
def clear_app_cache(app_name):
loading_cache = django.db.models.loading.cache
if django.VERSION[:2] < (1, 7):
loading_cache.app_models[app_name].clear()
else:
loading_cache.all_models[app_name].clear()
|
Clear django cache for models.
:param str ap_name: name of application to clear model cache
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L55-L66
| null |
""" Django specific utils.
Utils are used to work with different django versions.
"""
import django
from django.db import models
from django.http import QueryDict
from . import six
def get_model_by_name(model_name):
""" Get model by its name.
:param str model_name: name of model.
:return django.db.models.Model:
Example:
get_concrete_model_by_name('auth.User')
django.contrib.auth.models.User
"""
if isinstance(model_name, six.string_types) and \
len(model_name.split('.')) == 2:
app_name, model_name = model_name.split('.')
if django.VERSION[:2] < (1, 8):
model = models.get_model(app_name, model_name)
else:
from django.apps import apps
model = apps.get_model(app_name, model_name)
else:
raise ValueError("{0} is not a Django model".format(model_name))
return model
def get_model_name(model):
""" Get model name for the field.
Django 1.5 uses module_name, does not support model_name
Django 1.6 uses module_name and model_name
DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
"""
opts = model._meta
if django.VERSION[:2] < (1, 7):
model_name = opts.module_name
else:
model_name = opts.model_name
return model_name
def get_querydict(query):
if six.PY2:
return dict(QueryDict(query).iterlists())
else:
return dict(QueryDict(query).lists())
def get_models():
if django.VERSION[:2] < (1, 8):
return models.get_models()
else:
from django.apps import apps
return apps.get_models()
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.register
|
python
|
def register(self, resource=None, **kwargs):
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
|
Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L69-L109
| null |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
@property
def urls(self):
""" Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
"""
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
def update_urls(self, request, resource_name=None, ids=None):
""" Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
"""
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
def map_view(self, request):
""" Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
def documentation(self, request):
""" Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.urls
|
python
|
def urls(self):
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
|
Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L112-L135
| null |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
"""
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
@property
def update_urls(self, request, resource_name=None, ids=None):
""" Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
"""
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
def map_view(self, request):
""" Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
def documentation(self, request):
""" Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.update_urls
|
python
|
def update_urls(self, request, resource_name=None, ids=None):
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
|
Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L137-L166
| null |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
"""
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
@property
def urls(self):
""" Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
"""
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
def map_view(self, request):
""" Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
def documentation(self, request):
""" Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.map_view
|
python
|
def map_view(self, request):
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
|
Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L168-L189
|
[
"def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is None:\n http_host = request.META['SERVER_NAME']\n if request.META['SERVER_PORT'] not in ('80', '443'):\n http_host = \"{}:{}\".format(\n http_host, request.META['SERVER_PORT'])\n\n self.base_url = \"{}://{}\".format(\n request.META['wsgi.url_scheme'],\n http_host\n )\n self.api_url = \"{}{}\".format(self.base_url, request.path)\n self.api_url = self.api_url.rstrip(\"/\")\n\n if ids is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n\n if resource_name is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n"
] |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
"""
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
@property
def urls(self):
""" Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
"""
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
def update_urls(self, request, resource_name=None, ids=None):
""" Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
"""
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
def documentation(self, request):
""" Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.documentation
|
python
|
def documentation(self, request):
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
|
Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L191-L204
|
[
"def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is None:\n http_host = request.META['SERVER_NAME']\n if request.META['SERVER_PORT'] not in ('80', '443'):\n http_host = \"{}:{}\".format(\n http_host, request.META['SERVER_PORT'])\n\n self.base_url = \"{}://{}\".format(\n request.META['wsgi.url_scheme'],\n http_host\n )\n self.api_url = \"{}{}\".format(self.base_url, request.path)\n self.api_url = self.api_url.rstrip(\"/\")\n\n if ids is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n\n if resource_name is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n"
] |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
"""
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
@property
def urls(self):
""" Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
"""
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
def update_urls(self, request, resource_name=None, ids=None):
""" Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
"""
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
def map_view(self, request):
""" Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
def handler_view(self, request, resource_name, ids=None):
""" Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
pavlov99/jsonapi
|
jsonapi/api.py
|
API.handler_view
|
python
|
def handler_view(self, request, resource_name, ids=None):
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resource.Meta.allowed_methods
if request.method not in allowed_http_methods:
response = HttpResponseNotAllowed(
permitted_methods=allowed_http_methods)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
if resource.Meta.authenticators and not (
request.method == "GET" and
resource.Meta.disable_get_authentication):
user = resource.authenticate(request)
if user is None or not user.is_authenticated():
response = HttpResponse("Not Authenticated", status=401)
signal_response.send(
sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
kwargs = dict(request=request)
if ids is not None:
kwargs['ids'] = ids.split(",")
try:
if request.method == "GET":
response = self.handler_view_get(resource, **kwargs)
elif request.method == "POST":
response = self.handler_view_post(resource, **kwargs)
elif request.method == "PUT":
response = self.handler_view_put(resource, **kwargs)
elif request.method == "DELETE":
response = self.handler_view_delete(resource, **kwargs)
except JSONAPIError as e:
response = HttpResponse(
json.dumps({"errors": [e.data]}, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=e.status)
signal_response.send(sender=self, request=request, response=response,
duration=time.time() - time_start)
return response
|
Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L258-L312
|
[
"def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is None:\n http_host = request.META['SERVER_NAME']\n if request.META['SERVER_PORT'] not in ('80', '443'):\n http_host = \"{}:{}\".format(\n http_host, request.META['SERVER_PORT'])\n\n self.base_url = \"{}://{}\".format(\n request.META['wsgi.url_scheme'],\n http_host\n )\n self.api_url = \"{}{}\".format(self.base_url, request.path)\n self.api_url = self.api_url.rstrip(\"/\")\n\n if ids is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n\n if resource_name is not None:\n self.api_url = self.api_url.rsplit(\"/\", 1)[0]\n",
"def handler_view_get(self, resource, **kwargs):\n items = json.dumps(\n resource.get(**kwargs),\n cls=resource.Meta.encoder\n )\n return HttpResponse(items, content_type=self.CONTENT_TYPE)\n",
"def handler_view_post(self, resource, **kwargs):\n data = resource.post(**kwargs)\n if \"errors\" in data:\n response = HttpResponse(\n json.dumps(data, cls=DatetimeDecimalEncoder),\n content_type=self.CONTENT_TYPE, status=400)\n return response\n\n response = HttpResponse(\n json.dumps(data, cls=DatetimeDecimalEncoder),\n content_type=self.CONTENT_TYPE, status=201)\n\n items = data[\"data\"]\n items = items if isinstance(items, list) else [items]\n\n response[\"Location\"] = \"{}/{}\".format(\n resource.Meta.name,\n \",\".join([str(x[\"id\"]) for x in items])\n )\n return response\n",
"def handler_view_put(self, resource, **kwargs):\n if 'ids' not in kwargs:\n return HttpResponse(\"Request SHOULD have resource ids\", status=400)\n\n data = resource.put(**kwargs)\n if \"errors\" in data:\n response = HttpResponse(\n json.dumps(data, cls=DatetimeDecimalEncoder),\n content_type=self.CONTENT_TYPE, status=400)\n return response\n\n response = HttpResponse(\n json.dumps(data, cls=DatetimeDecimalEncoder),\n content_type=self.CONTENT_TYPE, status=200)\n return response\n",
"def handler_view_delete(self, resource, **kwargs):\n if 'ids' not in kwargs:\n return HttpResponse(\"Request SHOULD have resource ids\", status=400)\n\n response = resource.delete(**kwargs)\n return HttpResponse(\n response, content_type=self.CONTENT_TYPE, status=204)\n"
] |
class API(object):
""" API handler."""
CONTENT_TYPE = "application/vnd.api+json"
def __init__(self):
self._resources = []
self.base_url = None # base server url
self.api_url = None # api root url
@property
def resource_map(self):
""" Resource map of api.
.. versionadded:: 0.4.1
:return: resource name to resource mapping.
:rtype: dict
"""
return {r.Meta.name: r for r in self._resources}
@property
def model_resource_map(self):
return {
resource.Meta.model: resource
for resource in self.resource_map.values()
if hasattr(resource.Meta, 'model')
}
def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters
"""
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.name in self.resource_map:
raise ValueError('Resource {} already registered'.format(
resource.Meta.name))
if resource.Meta.name_plural in self.resource_map:
raise ValueError(
'Resource plural name {} conflicts with registered resource'.
format(resource.Meta.name))
resource_plural_names = {
r.Meta.name_plural for r in self.resource_map.values()
}
if resource.Meta.name in resource_plural_names:
raise ValueError(
'Resource name {} conflicts with other resource plural name'.
format(resource.Meta.name)
)
resource.Meta.api = self
self._resources.append(resource)
return resource
@property
def urls(self):
""" Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls
"""
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
resource_name), self.handler_view),
url(r'(?P<resource_name>{})/(?P<ids>[\w\-\,]+)$'.format(
resource_name), self.handler_view),
])
return urls
def update_urls(self, request, resource_name=None, ids=None):
""" Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None
"""
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
http_host, request.META['SERVER_PORT'])
self.base_url = "{}://{}".format(
request.META['wsgi.url_scheme'],
http_host
)
self.api_url = "{}{}".format(self.base_url, request.path)
self.api_url = self.api_url.rstrip("/")
if ids is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
if resource_name is not None:
self.api_url = self.api_url.rsplit("/", 1)[0]
def map_view(self, request):
""" Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self.resource_map.items()))
if not resource.Meta.authenticators or
resource.authenticate(request) is not None
]
}
response = json.dumps(resource_info)
return HttpResponse(response, content_type="application/vnd.api+json")
def documentation(self, request):
""" Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse
"""
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context)
def handler_view_get(self, resource, **kwargs):
items = json.dumps(
resource.get(**kwargs),
cls=resource.Meta.encoder
)
return HttpResponse(items, content_type=self.CONTENT_TYPE)
def handler_view_post(self, resource, **kwargs):
data = resource.post(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=201)
items = data["data"]
items = items if isinstance(items, list) else [items]
response["Location"] = "{}/{}".format(
resource.Meta.name,
",".join([str(x["id"]) for x in items])
)
return response
def handler_view_put(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
return response
def handler_view_delete(self, resource, **kwargs):
if 'ids' not in kwargs:
return HttpResponse("Request SHOULD have resource ids", status=400)
response = resource.delete(**kwargs)
return HttpResponse(
response, content_type=self.CONTENT_TYPE, status=204)
|
pavlov99/jsonapi
|
jsonapi/request_parser.py
|
RequestParser.parse
|
python
|
def parse(cls, querydict):
for key in querydict.keys():
if not any((key in JSONAPIQueryDict._fields,
cls.RE_FIELDS.match(key))):
msg = "Query parameter {} is not known".format(key)
raise ValueError(msg)
result = JSONAPIQueryDict(
distinct=cls.prepare_values(querydict.getlist('distinct')),
fields=cls.parse_fields(querydict),
filter=querydict.getlist('filter'),
include=cls.prepare_values(querydict.getlist('include')),
page=int(querydict.get('page')) if querydict.get('page') else None,
sort=cls.prepare_values(querydict.getlist('sort'))
)
return result
|
Parse querydict data.
There are expected agruments:
distinct, fields, filter, include, page, sort
Parameters
----------
querydict : django.http.request.QueryDict
MultiValueDict with query arguments.
Returns
-------
result : dict
dictionary in format {key: value}.
Raises
------
ValueError
If args consist of not know key.
|
train
|
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/request_parser.py#L23-L61
|
[
"def prepare_values(cls, values):\n return [x for value in values for x in value.split(\",\")]\n",
"def parse_fields(cls, querydict):\n fields = cls.prepare_values(querydict.getlist('fields'))\n fields_typed = []\n\n for key in querydict.keys():\n fields_match = cls.RE_FIELDS.match(key)\n\n if fields_match is not None:\n resource_name = fields_match.group(\"resource\")\n fields_typed.extend([\n (resource_name, value)\n for value in cls.prepare_values(querydict.getlist(key))\n ])\n\n if fields and fields_typed:\n raise ValueError(\"Either default or typed fields should be used\")\n\n return fields or fields_typed\n"
] |
class RequestParser(object):
""" Rarser for Django request.GET parameters."""
RE_FIELDS = re.compile('^fields\[(?P<resource>\w+)\]$')
@classmethod
@classmethod
def prepare_values(cls, values):
return [x for value in values for x in value.split(",")]
@classmethod
def parse_fields(cls, querydict):
fields = cls.prepare_values(querydict.getlist('fields'))
fields_typed = []
for key in querydict.keys():
fields_match = cls.RE_FIELDS.match(key)
if fields_match is not None:
resource_name = fields_match.group("resource")
fields_typed.extend([
(resource_name, value)
for value in cls.prepare_values(querydict.getlist(key))
])
if fields and fields_typed:
raise ValueError("Either default or typed fields should be used")
return fields or fields_typed
|
faide/py3o.template
|
py3o/template/main.py
|
detect_keep_boundary
|
python
|
def detect_keep_boundary(start, end, namespaces):
result_start, result_end = False, False
parent_start = start.getparent()
parent_end = end.getparent()
if parent_start.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_start = len(parent_start.getchildren()) > 1
if parent_end.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_end = len(parent_end.getchildren()) > 1
return result_start, result_end
|
a helper to inspect a link and see if we should keep the link boundary
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L49-L66
| null |
# -*- encoding: utf-8 -*-
import decimal
import logging
import os
import lxml.etree
import zipfile
from copy import copy
from io import BytesIO
from uuid import uuid4
from six.moves import urllib
from genshi.template import MarkupTemplate
from genshi.filters.transform import Transformer
from pyjon.utils import get_secure_filename
from py3o.template.decoder import Decoder, ForList
log = logging.getLogger(__name__)
# expressed in clark notation: http://www.jclark.com/xml/xmlns.htm
XML_NS = "{http://www.w3.org/XML/1998/namespace}"
GENSHI_URI = 'http://genshi.edgewall.org/'
PY3O_URI = 'http://py3o.org/'
# Images are stored in the "Pictures" directory and prefixed with "py3o-".
# Saving images in a sub-directory would be cleaner but doesn't seem to be
# supported...
PY3O_IMAGE_PREFIX = 'Pictures/py3o-'
class TemplateException(ValueError):
"""some client code is used to catching ValueErrors, let's keep the old
codebase hapy
"""
def __init__(self, message):
"""define the __init__ to handle message... for python3's sake
"""
self.message = message
def __str__(self):
return self.message
def move_siblings(
start, end, new_,
keep_start_boundary=False,
keep_end_boundary=False
):
"""a helper function that will replace a start/end node pair
by a new containing element, effectively moving all in-between siblings
This is particularly helpful to replace for /for loops in tables
with the content resulting from the iteration
This function call returns None. The parent xml tree is modified in place
@param start: the starting xml node
@type start: lxml.etree.Element
@param end: the ending xml node
@type end: lxml.etree.Element
@param new_: the new xml element that will replace the start/end pair
@type new_: lxlm.etree.Element
@param keep_start_boundary: Flag to let the function know if it copies
your start tag to the new_ node or not, Default value is False
@type keep_start_boundary: bool
@param keep_end_boundary: Flag to let the function know if it copies
your end tag to the new_ node or not, Default value is False
@type keep_end_boundary: bool
@returns: None
"""
old_ = start.getparent()
if keep_start_boundary:
new_.append(copy(start))
else:
if start.tail:
# copy the existing tail as text
new_.text = start.tail
# get all siblings
for node in start.itersiblings():
if node is not end:
new_.append(node)
elif node is end:
# if this is already the end boundary, then we are done
if keep_end_boundary:
new_.append(copy(node))
break
# replace start boundary with new node
old_.replace(start, new_)
# remove ending boundary we already copied it if needed
old_.remove(end)
def get_list_transformer(namespaces):
"""this function returns a transformer to
find all list elements and recompute their xml:id.
Because if we duplicate lists we create invalid XML.
Each list must have its own xml:id
This is important if you want to be able to reopen the produced
document wih an XML parser. LibreOffice will fix those ids itself
silently, but lxml.etree.parse will bork on such duplicated lists
"""
return Transformer(
'//list[namespace-uri()="%s"]' % namespaces.get(
'text'
)
).attr(
'{0}id'.format(XML_NS),
lambda *args: "list{0}".format(uuid4().hex)
)
def get_instructions(content_tree, namespaces):
# find all links that have a py3o
xpath_expr = "//text:a[starts-with(@xlink:href, 'py3o://')]"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
def get_user_fields(content_tree, namespaces):
field_expr = "//text:user-field-decl[starts-with(@text:name, 'py3o.')]"
return content_tree.xpath(
field_expr,
namespaces=namespaces
)
def get_soft_breaks(content_tree, namespaces):
xpath_expr = "//text:soft-page-break"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
move_siblings
|
python
|
def move_siblings(
start, end, new_,
keep_start_boundary=False,
keep_end_boundary=False
):
old_ = start.getparent()
if keep_start_boundary:
new_.append(copy(start))
else:
if start.tail:
# copy the existing tail as text
new_.text = start.tail
# get all siblings
for node in start.itersiblings():
if node is not end:
new_.append(node)
elif node is end:
# if this is already the end boundary, then we are done
if keep_end_boundary:
new_.append(copy(node))
break
# replace start boundary with new node
old_.replace(start, new_)
# remove ending boundary we already copied it if needed
old_.remove(end)
|
a helper function that will replace a start/end node pair
by a new containing element, effectively moving all in-between siblings
This is particularly helpful to replace for /for loops in tables
with the content resulting from the iteration
This function call returns None. The parent xml tree is modified in place
@param start: the starting xml node
@type start: lxml.etree.Element
@param end: the ending xml node
@type end: lxml.etree.Element
@param new_: the new xml element that will replace the start/end pair
@type new_: lxlm.etree.Element
@param keep_start_boundary: Flag to let the function know if it copies
your start tag to the new_ node or not, Default value is False
@type keep_start_boundary: bool
@param keep_end_boundary: Flag to let the function know if it copies
your end tag to the new_ node or not, Default value is False
@type keep_end_boundary: bool
@returns: None
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L69-L125
| null |
# -*- encoding: utf-8 -*-
import decimal
import logging
import os
import lxml.etree
import zipfile
from copy import copy
from io import BytesIO
from uuid import uuid4
from six.moves import urllib
from genshi.template import MarkupTemplate
from genshi.filters.transform import Transformer
from pyjon.utils import get_secure_filename
from py3o.template.decoder import Decoder, ForList
log = logging.getLogger(__name__)
# expressed in clark notation: http://www.jclark.com/xml/xmlns.htm
XML_NS = "{http://www.w3.org/XML/1998/namespace}"
GENSHI_URI = 'http://genshi.edgewall.org/'
PY3O_URI = 'http://py3o.org/'
# Images are stored in the "Pictures" directory and prefixed with "py3o-".
# Saving images in a sub-directory would be cleaner but doesn't seem to be
# supported...
PY3O_IMAGE_PREFIX = 'Pictures/py3o-'
class TemplateException(ValueError):
"""some client code is used to catching ValueErrors, let's keep the old
codebase hapy
"""
def __init__(self, message):
"""define the __init__ to handle message... for python3's sake
"""
self.message = message
def __str__(self):
return self.message
def detect_keep_boundary(start, end, namespaces):
"""a helper to inspect a link and see if we should keep the link boundary
"""
result_start, result_end = False, False
parent_start = start.getparent()
parent_end = end.getparent()
if parent_start.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_start = len(parent_start.getchildren()) > 1
if parent_end.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_end = len(parent_end.getchildren()) > 1
return result_start, result_end
def get_list_transformer(namespaces):
"""this function returns a transformer to
find all list elements and recompute their xml:id.
Because if we duplicate lists we create invalid XML.
Each list must have its own xml:id
This is important if you want to be able to reopen the produced
document wih an XML parser. LibreOffice will fix those ids itself
silently, but lxml.etree.parse will bork on such duplicated lists
"""
return Transformer(
'//list[namespace-uri()="%s"]' % namespaces.get(
'text'
)
).attr(
'{0}id'.format(XML_NS),
lambda *args: "list{0}".format(uuid4().hex)
)
def get_instructions(content_tree, namespaces):
# find all links that have a py3o
xpath_expr = "//text:a[starts-with(@xlink:href, 'py3o://')]"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
def get_user_fields(content_tree, namespaces):
field_expr = "//text:user-field-decl[starts-with(@text:name, 'py3o.')]"
return content_tree.xpath(
field_expr,
namespaces=namespaces
)
def get_soft_breaks(content_tree, namespaces):
xpath_expr = "//text:soft-page-break"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
get_list_transformer
|
python
|
def get_list_transformer(namespaces):
return Transformer(
'//list[namespace-uri()="%s"]' % namespaces.get(
'text'
)
).attr(
'{0}id'.format(XML_NS),
lambda *args: "list{0}".format(uuid4().hex)
)
|
this function returns a transformer to
find all list elements and recompute their xml:id.
Because if we duplicate lists we create invalid XML.
Each list must have its own xml:id
This is important if you want to be able to reopen the produced
document wih an XML parser. LibreOffice will fix those ids itself
silently, but lxml.etree.parse will bork on such duplicated lists
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L128-L145
| null |
# -*- encoding: utf-8 -*-
import decimal
import logging
import os
import lxml.etree
import zipfile
from copy import copy
from io import BytesIO
from uuid import uuid4
from six.moves import urllib
from genshi.template import MarkupTemplate
from genshi.filters.transform import Transformer
from pyjon.utils import get_secure_filename
from py3o.template.decoder import Decoder, ForList
log = logging.getLogger(__name__)
# expressed in clark notation: http://www.jclark.com/xml/xmlns.htm
XML_NS = "{http://www.w3.org/XML/1998/namespace}"
GENSHI_URI = 'http://genshi.edgewall.org/'
PY3O_URI = 'http://py3o.org/'
# Images are stored in the "Pictures" directory and prefixed with "py3o-".
# Saving images in a sub-directory would be cleaner but doesn't seem to be
# supported...
PY3O_IMAGE_PREFIX = 'Pictures/py3o-'
class TemplateException(ValueError):
"""some client code is used to catching ValueErrors, let's keep the old
codebase hapy
"""
def __init__(self, message):
"""define the __init__ to handle message... for python3's sake
"""
self.message = message
def __str__(self):
return self.message
def detect_keep_boundary(start, end, namespaces):
"""a helper to inspect a link and see if we should keep the link boundary
"""
result_start, result_end = False, False
parent_start = start.getparent()
parent_end = end.getparent()
if parent_start.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_start = len(parent_start.getchildren()) > 1
if parent_end.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_end = len(parent_end.getchildren()) > 1
return result_start, result_end
def move_siblings(
start, end, new_,
keep_start_boundary=False,
keep_end_boundary=False
):
"""a helper function that will replace a start/end node pair
by a new containing element, effectively moving all in-between siblings
This is particularly helpful to replace for /for loops in tables
with the content resulting from the iteration
This function call returns None. The parent xml tree is modified in place
@param start: the starting xml node
@type start: lxml.etree.Element
@param end: the ending xml node
@type end: lxml.etree.Element
@param new_: the new xml element that will replace the start/end pair
@type new_: lxlm.etree.Element
@param keep_start_boundary: Flag to let the function know if it copies
your start tag to the new_ node or not, Default value is False
@type keep_start_boundary: bool
@param keep_end_boundary: Flag to let the function know if it copies
your end tag to the new_ node or not, Default value is False
@type keep_end_boundary: bool
@returns: None
"""
old_ = start.getparent()
if keep_start_boundary:
new_.append(copy(start))
else:
if start.tail:
# copy the existing tail as text
new_.text = start.tail
# get all siblings
for node in start.itersiblings():
if node is not end:
new_.append(node)
elif node is end:
# if this is already the end boundary, then we are done
if keep_end_boundary:
new_.append(copy(node))
break
# replace start boundary with new node
old_.replace(start, new_)
# remove ending boundary we already copied it if needed
old_.remove(end)
def get_instructions(content_tree, namespaces):
# find all links that have a py3o
xpath_expr = "//text:a[starts-with(@xlink:href, 'py3o://')]"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
def get_user_fields(content_tree, namespaces):
field_expr = "//text:user-field-decl[starts-with(@text:name, 'py3o.')]"
return content_tree.xpath(
field_expr,
namespaces=namespaces
)
def get_soft_breaks(content_tree, namespaces):
xpath_expr = "//text:soft-page-break"
return content_tree.xpath(
xpath_expr,
namespaces=namespaces
)
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.__prepare_namespaces
|
python
|
def __prepare_namespaces(self):
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
|
create proper namespaces for our document
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L208-L232
| null |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.get_user_instructions
|
python
|
def get_user_instructions(self):
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
|
Public method to help report engine to find all instructions
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L234-L245
|
[
"def get_instructions(content_tree, namespaces):\n # find all links that have a py3o\n xpath_expr = \"//text:a[starts-with(@xlink:href, 'py3o://')]\"\n return content_tree.xpath(\n xpath_expr,\n namespaces=namespaces\n )\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.get_user_instructions_mapping
|
python
|
def get_user_instructions_mapping(self):
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
|
Public method to get the mapping of all
variables defined in the template
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L252-L299
|
[
"def add_child(self, child):\n child.parent = self\n self.childs.append(child)\n",
"def add_attr(self, attr):\n self.attrs.append(attr)\n",
"def decode_py3o_instruction(self, instruction):\n # We convert py3o for loops into valid python for loop\n inst_str = \"for \" + instruction.split('\"')[1] + \": pass\\n\"\n return self.decode(inst_str)\n",
"def get_user_instructions(self):\n \"\"\" Public method to help report engine to find all instructions\n \"\"\"\n res = []\n # TODO: Check if instructions can be stored in other content_trees\n for e in get_instructions(self.content_trees[0], self.namespaces):\n childs = e.getchildren()\n if childs:\n res.extend([c.text for c in childs])\n else:\n res.append(e.text)\n return res\n",
"def get_user_variables(self):\n \"\"\"a public method to help report engines to introspect\n a template and find what data it needs and how it will be\n used\n returns a list of user variable names without starting 'py3o.'\"\"\"\n # TODO: Check if some user fields are stored in other content_trees\n return [\n e.get('{%s}name' % e.nsmap.get('text'))[5:]\n for e in get_user_fields(self.content_trees[0], self.namespaces)\n ]\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.handle_link
|
python
|
def handle_link(self, link, py3o_base, closing_link):
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
|
transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L329-L412
|
[
"def detect_keep_boundary(start, end, namespaces):\n \"\"\"a helper to inspect a link and see if we should keep the link boundary\n \"\"\"\n result_start, result_end = False, False\n parent_start = start.getparent()\n parent_end = end.getparent()\n\n if parent_start.tag == \"{%s}p\" % namespaces['text']:\n # more than one child in the containing paragraph ?\n # we keep the boundary\n result_start = len(parent_start.getchildren()) > 1\n\n if parent_end.tag == \"{%s}p\" % namespaces['text']:\n # more than one child in the containing paragraph ?\n # we keep the boundary\n result_end = len(parent_end.getchildren()) > 1\n\n return result_start, result_end\n",
"def move_siblings(\n start, end, new_,\n keep_start_boundary=False,\n keep_end_boundary=False\n):\n \"\"\"a helper function that will replace a start/end node pair\n by a new containing element, effectively moving all in-between siblings\n This is particularly helpful to replace for /for loops in tables\n with the content resulting from the iteration\n\n This function call returns None. The parent xml tree is modified in place\n\n @param start: the starting xml node\n @type start: lxml.etree.Element\n\n @param end: the ending xml node\n @type end: lxml.etree.Element\n\n @param new_: the new xml element that will replace the start/end pair\n @type new_: lxlm.etree.Element\n\n @param keep_start_boundary: Flag to let the function know if it copies\n your start tag to the new_ node or not, Default value is False\n @type keep_start_boundary: bool\n\n @param keep_end_boundary: Flag to let the function know if it copies\n your end tag to the new_ node or not, Default value is False\n @type keep_end_boundary: bool\n\n @returns: None\n \"\"\"\n old_ = start.getparent()\n if keep_start_boundary:\n new_.append(copy(start))\n\n else:\n if start.tail:\n # copy the existing tail as text\n new_.text = start.tail\n\n # get all siblings\n for node in start.itersiblings():\n if node is not end:\n new_.append(node)\n\n elif node is end:\n # if this is already the end boundary, then we are done\n if keep_end_boundary:\n new_.append(copy(node))\n\n break\n\n # replace start boundary with new node\n old_.replace(start, new_)\n\n # remove ending boundary we already copied it if needed\n old_.remove(end)\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.get_user_variables
|
python
|
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
|
a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L414-L423
|
[
"def get_user_fields(content_tree, namespaces):\n field_expr = \"//text:user-field-decl[starts-with(@text:name, 'py3o.')]\"\n return content_tree.xpath(\n field_expr,\n namespaces=namespaces\n )\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.__prepare_usertexts
|
python
|
def __prepare_usertexts(self):
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
|
Replace user-type text fields that start with "py3o." with genshi
instructions.
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L452-L532
| null |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.__replace_image_links
|
python
|
def __replace_image_links(self):
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
|
Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L534-L569
| null |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.__add_images_to_manifest
|
python
|
def __add_images_to_manifest(self):
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
|
Add entries for py3o images into the manifest file.
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L571-L597
| null |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.render_tree
|
python
|
def render_tree(self, data):
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
|
prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L599-L680
|
[
"def remove_soft_breaks(self):\n for soft_break in get_soft_breaks(\n self.content_trees[0], self.namespaces):\n soft_break.getparent().remove(soft_break)\n",
"def handle_instructions(content_trees, namespaces):\n\n opened_starts = list()\n starting_tags = list()\n closing_tags = dict()\n\n for content_tree in content_trees:\n for link in get_instructions(content_tree, namespaces):\n py3o_statement = urllib.parse.unquote(\n link.attrib['{%s}href' % namespaces['xlink']]\n )\n # remove the py3o://\n py3o_base = py3o_statement[7:]\n\n if not py3o_base.startswith(\"/\"):\n opened_starts.append(link)\n starting_tags.append((link, py3o_base))\n\n else:\n if not opened_starts:\n raise TemplateException(\n \"No open instruction for %s\" % py3o_base)\n\n closing_tags[id(opened_starts.pop())] = link\n\n return starting_tags, closing_tags\n",
"def handle_link(self, link, py3o_base, closing_link):\n \"\"\"transform a py3o link into a proper Genshi statement\n rebase a py3o link at a proper place in the tree\n to be ready for Genshi replacement\n \"\"\"\n # OLD open office version\n if link.text is not None and link.text.strip():\n if not link.text == py3o_base:\n msg = \"url and text do not match in '%s'\" % link.text\n raise TemplateException(msg)\n\n # new open office version\n elif len(link):\n if not link[0].text == py3o_base:\n msg = \"url and text do not match in '%s'\" % link.text\n raise TemplateException(msg)\n else:\n raise TemplateException(\"Link text not found\")\n\n # find out if the instruction is inside a table\n parent = link.getparent()\n keep_start_boundary = False\n keep_end_boundary = False\n\n if parent.getparent() is not None and parent.getparent().tag == (\n \"{%s}table-cell\" % self.namespaces['table']\n ):\n # we are in a table\n opening_paragraph = parent\n opening_cell = opening_paragraph.getparent()\n\n # same for closing\n closing_paragraph = closing_link.getparent()\n closing_cell = closing_paragraph.getparent()\n\n if opening_cell == closing_cell:\n # block is fully in a single cell\n opening_row = opening_paragraph\n closing_row = closing_paragraph\n else:\n opening_row = opening_cell.getparent()\n closing_row = closing_cell.getparent()\n\n elif parent.tag == \"{%s}p\" % self.namespaces['text']:\n # if we are using text we want to keep start/end nodes\n keep_start_boundary, keep_end_boundary = detect_keep_boundary(\n link, closing_link, self.namespaces\n )\n # we are in a text paragraph\n opening_row = parent\n closing_row = closing_link.getparent()\n\n else:\n raise NotImplementedError(\n \"We handle urls in tables or text paragraph only\"\n )\n\n # max split is one\n instruction, instruction_value = py3o_base.split(\"=\", 1)\n instruction_value = instruction_value.strip('\"')\n\n attribs = dict()\n attribs['{%s}strip' % GENSHI_URI] = 'True'\n attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value\n\n genshi_node = lxml.etree.Element(\n 'span',\n attrib=attribs,\n nsmap={'py': GENSHI_URI},\n )\n\n link.getparent().remove(link)\n closing_link.getparent().remove(closing_link)\n\n try:\n move_siblings(\n opening_row, closing_row, genshi_node,\n keep_start_boundary=keep_start_boundary,\n keep_end_boundary=keep_end_boundary,\n )\n except ValueError as e:\n log.exception(e)\n raise TemplateException(\"Could not move siblings for '%s'\" %\n py3o_base)\n",
"def __prepare_userfield_decl(self):\n self.field_info = dict()\n\n for content_tree in self.content_trees:\n # here we gather the fields info in one pass to be able to avoid\n # doing the same operation multiple times.\n for userfield in get_user_fields(content_tree, self.namespaces):\n\n value = userfield.attrib[\n '{%s}name' % self.namespaces['text']\n ][5:]\n\n value_type = userfield.attrib.get(\n '{%s}value-type' % self.namespaces['office'],\n 'string'\n )\n\n value_datastyle_name = userfield.attrib.get(\n '{%s}data-style-name' % self.namespaces['style'],\n )\n\n self.field_info[value] = {\n \"name\": value,\n \"value_type\": value_type,\n 'value_datastyle_name': value_datastyle_name,\n }\n",
"def __prepare_usertexts(self):\n \"\"\"Replace user-type text fields that start with \"py3o.\" with genshi\n instructions.\n \"\"\"\n\n field_expr = \"//text:user-field-get[starts-with(@text:name, 'py3o.')]\"\n\n for content_tree in self.content_trees:\n\n for userfield in content_tree.xpath(\n field_expr,\n namespaces=self.namespaces\n ):\n parent = userfield.getparent()\n value = userfield.attrib[\n '{%s}name' % self.namespaces['text']\n ][5:]\n value_type = self.field_info[value]['value_type']\n\n # we try to override global var type with local settings\n value_type_attr = '{%s}value-type' % self.namespaces['office']\n rec = 0\n parent_node = parent\n\n # special case for float which has a value info on top level\n # overriding local value\n found_node = False\n while rec <= 5:\n if parent_node is None:\n break\n\n # find an ancestor with an office:value-type attribute\n # this is the case when you are inside a table\n if value_type_attr in parent_node.attrib:\n value_type = parent_node.attrib[value_type_attr]\n found_node = True\n break\n\n rec += 1\n parent_node = parent_node.getparent()\n\n if value_type == 'float':\n value_attr = '{%s}value' % self.namespaces['office']\n rec = 0\n\n if found_node:\n parent_node.attrib[value_attr] = \"${%s}\" % value\n else:\n parent_node = userfield\n while rec <= 7:\n if parent_node is None:\n break\n\n if value_attr in parent_node.attrib:\n parent_node.attrib[value_attr] = \"${%s}\" % value\n break\n\n rec += 1\n parent_node = parent_node.getparent()\n\n value = \"format_float(%s)\" % value\n\n if value_type == 'percentage':\n del parent_node.attrib[value_attr]\n value = \"format_percentage(%s)\" % value\n parent_node.attrib[value_type_attr] = \"string\"\n\n attribs = dict()\n attribs['{%s}strip' % GENSHI_URI] = 'True'\n attribs['{%s}content' % GENSHI_URI] = value\n\n genshi_node = lxml.etree.Element(\n 'span',\n attrib=attribs,\n nsmap={'py': GENSHI_URI}\n )\n\n if userfield.tail:\n genshi_node.tail = userfield.tail\n\n parent.replace(userfield, genshi_node)\n",
"def __replace_image_links(self):\n \"\"\"Replace links of placeholder images (the name of which starts with\n \"py3o.\") to point to a file saved the \"Pictures\" directory of the\n archive.\n \"\"\"\n\n image_expr = \"//draw:frame[starts-with(@draw:name, 'py3o.')]\"\n\n for content_tree in self.content_trees:\n\n # Find draw:frame tags.\n for draw_frame in content_tree.xpath(\n image_expr,\n namespaces=self.namespaces\n ):\n # Find the identifier of the image (py3o.[identifier]).\n image_id = draw_frame.attrib[\n '{%s}name' % self.namespaces['draw']\n ][5:]\n if image_id not in self.images:\n if not self.ignore_undefined_variables:\n raise TemplateException(\n \"Can't find data for the image named 'py3o.%s'; \"\n \"make sure it has been added with the \"\n \"set_image_path or set_image_data methods.\"\n % image_id\n )\n else:\n continue\n\n # Replace the xlink:href attribute of the image to point to\n # ours.\n image = draw_frame[0]\n image.attrib[\n '{%s}href' % self.namespaces['xlink']\n ] = PY3O_IMAGE_PREFIX + image_id\n",
"def __add_images_to_manifest(self):\n \"\"\"Add entries for py3o images into the manifest file.\"\"\"\n\n xpath_expr = \"//manifest:manifest[1]\"\n\n for content_tree in self.content_trees:\n\n # Find manifest:manifest tags.\n manifest_e = content_tree.xpath(\n xpath_expr,\n namespaces=self.namespaces\n )\n if not manifest_e:\n continue\n\n for identifier in self.images.keys():\n # Add a manifest:file-entry tag.\n lxml.etree.SubElement(\n manifest_e[0],\n '{%s}file-entry' % self.namespaces['manifest'],\n attrib={\n '{%s}full-path' % self.namespaces['manifest']: (\n PY3O_IMAGE_PREFIX + identifier\n ),\n '{%s}media-type' % self.namespaces['manifest']: '',\n }\n )\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.render_flow
|
python
|
def render_flow(self, data):
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
|
render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L682-L694
|
[
"def render_tree(self, data):\n \"\"\"prepare the flows without saving to file\n this method has been decoupled from render_flow to allow better\n unit testing\n \"\"\"\n # TODO: find a way to make this localization aware...\n # because ATM it formats texts using French style numbers...\n # best way would be to let the user inject its own vars...\n # but this would not work on fusion servers...\n # so we must find a way to localize this a bit... or remove it and\n # consider our caller must pre - render its variables to the desired\n # locale...?\n new_data = dict(\n decimal=decimal,\n format_float=(\n lambda val: (\n isinstance(\n val, decimal.Decimal\n ) or isinstance(\n val, float\n )\n ) and str(val).replace('.', ',') or val\n ),\n format_percentage=(\n lambda val: (\"%0.2f %%\" % val).replace('.', ',')\n )\n )\n\n # Soft page breaks are hints for applications for rendering a page\n # break. Soft page breaks in for loops may compromise the paragraph\n # formatting especially the margins. Open-/LibreOffice will regenerate\n # the page breaks when displaying the document. Therefore it is save to\n # remove them.\n self.remove_soft_breaks()\n\n # first we need to transform the py3o template into a valid\n # Genshi template.\n starting_tags, closing_tags = self.handle_instructions(\n self.content_trees,\n self.namespaces\n )\n parents = [tag[0].getparent() for tag in starting_tags]\n linknum = len(parents)\n parentnum = len(set(parents))\n if not linknum == parentnum:\n raise TemplateException(\n \"Every py3o link instruction should be on its own line\"\n )\n\n for link, py3o_base in starting_tags:\n self.handle_link(\n link,\n py3o_base,\n closing_tags[id(link)]\n )\n\n self.__prepare_userfield_decl()\n self.__prepare_usertexts()\n\n self.__replace_image_links()\n self.__add_images_to_manifest()\n\n for fnum, content_tree in enumerate(self.content_trees):\n content = lxml.etree.tostring(content_tree.getroot())\n if self.ignore_undefined_variables:\n template = MarkupTemplate(content, lookup='lenient')\n else:\n template = MarkupTemplate(content)\n\n # then we need to render the genshi template itself by\n # providing the data to genshi\n\n template_dict = {}\n template_dict.update(data.items())\n template_dict.update(new_data.items())\n\n self.output_streams.append(\n (\n self.templated_files[fnum],\n template.generate(**template_dict)\n )\n )\n",
"def __save_output(self):\n \"\"\"Saves the output into a native OOo document format.\n \"\"\"\n out = zipfile.ZipFile(self.outputfilename, 'w')\n\n for info_zip in self.infile.infolist():\n\n if info_zip.filename in self.templated_files:\n # Template file - we have edited these.\n\n # get a temp file\n streamout = open(get_secure_filename(), \"w+b\")\n fname, output_stream = self.output_streams[\n self.templated_files.index(info_zip.filename)\n ]\n\n transformer = get_list_transformer(self.namespaces)\n remapped_stream = output_stream | transformer\n\n # write the whole stream to it\n for chunk in remapped_stream.serialize():\n streamout.write(chunk.encode('utf-8'))\n yield True\n\n # close the temp file to flush all data and make sure we get\n # it back when writing to the zip archive.\n streamout.close()\n\n # write the full file to archive\n out.write(streamout.name, fname)\n\n # remove temp file\n os.unlink(streamout.name)\n\n else:\n # Copy other files straight from the source archive.\n out.writestr(info_zip, self.infile.read(info_zip.filename))\n\n # Save images in the \"Pictures\" sub-directory of the archive.\n for identifier, data in self.images.items():\n out.writestr(PY3O_IMAGE_PREFIX + identifier, data)\n\n # close the zipfile before leaving\n out.close()\n yield True\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.set_image_path
|
python
|
def set_image_path(self, identifier, path):
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
|
Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L707-L720
|
[
"def set_image_data(self, identifier, data):\n \"\"\"Set data for an image mentioned in the template.\n\n @param identifier: Identifier of the image; refer to the image in the\n template by setting \"py3o.[identifier]\" as the name of that image.\n @type identifier: string\n\n @param data: Contents of the image.\n @type data: binary\n \"\"\"\n\n self.images[identifier] = data\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
faide/py3o.template
|
py3o/template/main.py
|
Template.__save_output
|
python
|
def __save_output(self):
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
Saves the output into a native OOo document format.
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L735-L779
|
[
"def get_list_transformer(namespaces):\n \"\"\"this function returns a transformer to\n find all list elements and recompute their xml:id.\n Because if we duplicate lists we create invalid XML.\n Each list must have its own xml:id\n\n This is important if you want to be able to reopen the produced\n document wih an XML parser. LibreOffice will fix those ids itself\n silently, but lxml.etree.parse will bork on such duplicated lists\n \"\"\"\n return Transformer(\n '//list[namespace-uri()=\"%s\"]' % namespaces.get(\n 'text'\n )\n ).attr(\n '{0}id'.format(XML_NS),\n lambda *args: \"list{0}\".format(uuid4().hex)\n )\n"
] |
class Template(object):
templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml']
def __init__(self, template, outfile, ignore_undefined_variables=False):
"""A template object exposes the API to render it to an OpenOffice
document.
@param template: a py3o template file. ie: a OpenDocument with the
proper py3o markups
@type template: a string representing the full path name to a py3o
template file.
@param outfile: the desired file name for the resulting ODT document
@type outfile: a string representing the full filename for output
@param ignore_undefined_variables: Not defined variables are replaced
with an empty string during template rendering if True
@type ignore_undefined_variables: boolean. Default is False
"""
self.template = template
self.outputfilename = outfile
self.infile = zipfile.ZipFile(self.template, 'r')
self.content_trees = [
lxml.etree.parse(BytesIO(self.infile.read(filename)))
for filename in self.templated_files
]
self.tree_roots = [tree.getroot() for tree in self.content_trees]
self.__prepare_namespaces()
self.images = {}
self.output_streams = []
self.ignore_undefined_variables = ignore_undefined_variables
def __prepare_namespaces(self):
"""create proper namespaces for our document
"""
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
def get_user_instructions(self):
""" Public method to help report engine to find all instructions
"""
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.append(e.text)
return res
def remove_soft_breaks(self):
for soft_break in get_soft_breaks(
self.content_trees[0], self.namespaces):
soft_break.getparent().remove(soft_break)
def get_user_instructions_mapping(self):
""" Public method to get the mapping of all
variables defined in the template
"""
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
@staticmethod
def handle_instructions(content_trees, namespaces):
opened_starts = list()
starting_tags = list()
closing_tags = dict()
for content_tree in content_trees:
for link in get_instructions(content_tree, namespaces):
py3o_statement = urllib.parse.unquote(
link.attrib['{%s}href' % namespaces['xlink']]
)
# remove the py3o://
py3o_base = py3o_statement[7:]
if not py3o_base.startswith("/"):
opened_starts.append(link)
starting_tags.append((link, py3o_base))
else:
if not opened_starts:
raise TemplateException(
"No open instruction for %s" % py3o_base)
closing_tags[id(opened_starts.pop())] = link
return starting_tags, closing_tags
def handle_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement
rebase a py3o link at a proper place in the tree
to be ready for Genshi replacement
"""
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(link):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
def get_user_variables(self):
"""a public method to help report engines to introspect
a template and find what data it needs and how it will be
used
returns a list of user variable names without starting 'py3o.'"""
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
]
def __prepare_userfield_decl(self):
self.field_info = dict()
for content_tree in self.content_trees:
# here we gather the fields info in one pass to be able to avoid
# doing the same operation multiple times.
for userfield in get_user_fields(content_tree, self.namespaces):
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = userfield.attrib.get(
'{%s}value-type' % self.namespaces['office'],
'string'
)
value_datastyle_name = userfield.attrib.get(
'{%s}data-style-name' % self.namespaces['style'],
)
self.field_info[value] = {
"name": value,
"value_type": value_type,
'value_datastyle_name': value_datastyle_name,
}
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_node)
def __replace_image_links(self):
"""Replace links of placeholder images (the name of which starts with
"py3o.") to point to a file saved the "Pictures" directory of the
archive.
"""
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]"
for content_tree in self.content_trees:
# Find draw:frame tags.
for draw_frame in content_tree.xpath(
image_expr,
namespaces=self.namespaces
):
# Find the identifier of the image (py3o.[identifier]).
image_id = draw_frame.attrib[
'{%s}name' % self.namespaces['draw']
][5:]
if image_id not in self.images:
if not self.ignore_undefined_variables:
raise TemplateException(
"Can't find data for the image named 'py3o.%s'; "
"make sure it has been added with the "
"set_image_path or set_image_data methods."
% image_id
)
else:
continue
# Replace the xlink:href attribute of the image to point to
# ours.
image = draw_frame[0]
image.attrib[
'{%s}href' % self.namespaces['xlink']
] = PY3O_IMAGE_PREFIX + image_id
def __add_images_to_manifest(self):
"""Add entries for py3o images into the manifest file."""
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
def render_tree(self, data):
"""prepare the flows without saving to file
this method has been decoupled from render_flow to allow better
unit testing
"""
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
def render_flow(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of user data. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status
def render(self, data):
"""render the OpenDocument with the user data
@param data: the input stream of userdata. This should be a dictionary
mapping, keys being the values accessible to your report.
@type data: dictionary
"""
for status in self.render_flow(data):
if not status:
raise TemplateException("unknown template error")
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param path: Image path on the file system
@type path: string
"""
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close()
def set_image_data(self, identifier, data):
"""Set data for an image mentioned in the template.
@param identifier: Identifier of the image; refer to the image in the
template by setting "py3o.[identifier]" as the name of that image.
@type identifier: string
@param data: Contents of the image.
@type data: binary
"""
self.images[identifier] = data
|
faide/py3o.template
|
py3o/template/decoder.py
|
ForList.__recur_to_dict
|
python
|
def __recur_to_dict(forlist, data_dict, res):
# First we go through all attrs from the ForList and add respective
# keys on the dict.
for a in forlist.attrs:
a_list = a.split('.')
if len(a_list) == 1:
res = data_dict[a_list[0]]
return res
if a_list[0] in data_dict:
tmp = res
for i in a_list[1:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
if len(a_list) == 1:
tmp[a_list[0]] = data_dict[a_list[0]]
else:
tmp[a_list[-1]] = reduce(
getattr,
a_list[1:],
data_dict[a_list[0]]
)
# Then create a list for all children,
# modify the datadict to fit the new child
# and call myself
for c in forlist.childs:
it = c.name.split('.')
res[it[-1]] = []
for i, val in enumerate(
reduce(getattr, it[1:], data_dict[it[0]])
):
new_data_dict = {c.var_from: val}
if len(res[it[-1]]) <= i:
res[it[-1]].append({})
res[it[-1]] = ForList.__recur_to_dict(
c, new_data_dict, res[it[-1]][i]
)
return res
|
Recursive function that fills up the dictionary
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L52-L92
|
[
"def __recur_to_dict(forlist, data_dict, res):\n \"\"\"Recursive function that fills up the dictionary\n \"\"\"\n # First we go through all attrs from the ForList and add respective\n # keys on the dict.\n for a in forlist.attrs:\n a_list = a.split('.')\n if len(a_list) == 1:\n res = data_dict[a_list[0]]\n return res\n if a_list[0] in data_dict:\n tmp = res\n for i in a_list[1:-1]:\n if not i in tmp:\n tmp[i] = {}\n tmp = tmp[i]\n if len(a_list) == 1:\n tmp[a_list[0]] = data_dict[a_list[0]]\n else:\n tmp[a_list[-1]] = reduce(\n getattr,\n a_list[1:],\n data_dict[a_list[0]]\n )\n # Then create a list for all children,\n # modify the datadict to fit the new child\n # and call myself\n for c in forlist.childs:\n it = c.name.split('.')\n res[it[-1]] = []\n for i, val in enumerate(\n reduce(getattr, it[1:], data_dict[it[0]])\n ):\n new_data_dict = {c.var_from: val}\n if len(res[it[-1]]) <= i:\n res[it[-1]].append({})\n res[it[-1]] = ForList.__recur_to_dict(\n c, new_data_dict, res[it[-1]][i]\n )\n\n return res\n"
] |
class ForList(object):
def __init__(self, name, var_from):
self.name = str(name)
self.childs = []
self.attrs = []
self._parent = None
self.var_from = var_from
def __eq__(self, other):
return self.name == other.name
def add_child(self, child):
child.parent = self
self.childs.append(child)
def add_attr(self, attr):
self.attrs.append(attr)
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, parent):
self._parent = parent
@staticmethod
@staticmethod
def to_dict(for_lists, global_vars, data_dict):
""" Construct a dict object from a list of ForList object
:param for_lists: list of for_list
:param global_vars: list of global vars to add
:param data_dict: data from an orm-like object (with dot notation)
:return: a dict representation of the ForList objects
"""
res = {}
# The first level is a little bit special
# Manage global variables
for a in global_vars:
a_list = a.split('.')
tmp = res
for i in a_list[:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
tmp[a_list[-1]] = reduce(getattr, a_list[1:], data_dict[a_list[0]])
# Then manage for lists recursively
for for_list in for_lists:
it = for_list.name.split('.')
tmp = res
for i in it[:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
if not it[-1] in tmp:
tmp[it[-1]] = []
tmp = tmp[it[-1]]
if not it[0] in data_dict:
continue
if len(it) == 1:
loop = enumerate(data_dict[it[0]])
else:
loop = enumerate(reduce(getattr, it[-1:], data_dict[it[0]]))
for i, val in loop:
new_data_dict = {for_list.var_from: val}
# We append a new dict only if we need
if len(tmp) <= i:
tmp.append({})
# Call myself with new context, and get result
tmp[i] = ForList.__recur_to_dict(
for_list, new_data_dict, tmp[i]
)
return res
|
faide/py3o.template
|
py3o/template/decoder.py
|
ForList.to_dict
|
python
|
def to_dict(for_lists, global_vars, data_dict):
res = {}
# The first level is a little bit special
# Manage global variables
for a in global_vars:
a_list = a.split('.')
tmp = res
for i in a_list[:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
tmp[a_list[-1]] = reduce(getattr, a_list[1:], data_dict[a_list[0]])
# Then manage for lists recursively
for for_list in for_lists:
it = for_list.name.split('.')
tmp = res
for i in it[:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
if not it[-1] in tmp:
tmp[it[-1]] = []
tmp = tmp[it[-1]]
if not it[0] in data_dict:
continue
if len(it) == 1:
loop = enumerate(data_dict[it[0]])
else:
loop = enumerate(reduce(getattr, it[-1:], data_dict[it[0]]))
for i, val in loop:
new_data_dict = {for_list.var_from: val}
# We append a new dict only if we need
if len(tmp) <= i:
tmp.append({})
# Call myself with new context, and get result
tmp[i] = ForList.__recur_to_dict(
for_list, new_data_dict, tmp[i]
)
return res
|
Construct a dict object from a list of ForList object
:param for_lists: list of for_list
:param global_vars: list of global vars to add
:param data_dict: data from an orm-like object (with dot notation)
:return: a dict representation of the ForList objects
|
train
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L95-L142
|
[
"def __recur_to_dict(forlist, data_dict, res):\n \"\"\"Recursive function that fills up the dictionary\n \"\"\"\n # First we go through all attrs from the ForList and add respective\n # keys on the dict.\n for a in forlist.attrs:\n a_list = a.split('.')\n if len(a_list) == 1:\n res = data_dict[a_list[0]]\n return res\n if a_list[0] in data_dict:\n tmp = res\n for i in a_list[1:-1]:\n if not i in tmp:\n tmp[i] = {}\n tmp = tmp[i]\n if len(a_list) == 1:\n tmp[a_list[0]] = data_dict[a_list[0]]\n else:\n tmp[a_list[-1]] = reduce(\n getattr,\n a_list[1:],\n data_dict[a_list[0]]\n )\n # Then create a list for all children,\n # modify the datadict to fit the new child\n # and call myself\n for c in forlist.childs:\n it = c.name.split('.')\n res[it[-1]] = []\n for i, val in enumerate(\n reduce(getattr, it[1:], data_dict[it[0]])\n ):\n new_data_dict = {c.var_from: val}\n if len(res[it[-1]]) <= i:\n res[it[-1]].append({})\n res[it[-1]] = ForList.__recur_to_dict(\n c, new_data_dict, res[it[-1]][i]\n )\n\n return res\n"
] |
class ForList(object):
def __init__(self, name, var_from):
self.name = str(name)
self.childs = []
self.attrs = []
self._parent = None
self.var_from = var_from
def __eq__(self, other):
return self.name == other.name
def add_child(self, child):
child.parent = self
self.childs.append(child)
def add_attr(self, attr):
self.attrs.append(attr)
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, parent):
self._parent = parent
@staticmethod
def __recur_to_dict(forlist, data_dict, res):
"""Recursive function that fills up the dictionary
"""
# First we go through all attrs from the ForList and add respective
# keys on the dict.
for a in forlist.attrs:
a_list = a.split('.')
if len(a_list) == 1:
res = data_dict[a_list[0]]
return res
if a_list[0] in data_dict:
tmp = res
for i in a_list[1:-1]:
if not i in tmp:
tmp[i] = {}
tmp = tmp[i]
if len(a_list) == 1:
tmp[a_list[0]] = data_dict[a_list[0]]
else:
tmp[a_list[-1]] = reduce(
getattr,
a_list[1:],
data_dict[a_list[0]]
)
# Then create a list for all children,
# modify the datadict to fit the new child
# and call myself
for c in forlist.childs:
it = c.name.split('.')
res[it[-1]] = []
for i, val in enumerate(
reduce(getattr, it[1:], data_dict[it[0]])
):
new_data_dict = {c.var_from: val}
if len(res[it[-1]]) <= i:
res[it[-1]].append({})
res[it[-1]] = ForList.__recur_to_dict(
c, new_data_dict, res[it[-1]][i]
)
return res
@staticmethod
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
socket_recvall
|
python
|
def socket_recvall(socket, length, bufsize=4096):
data = b""
while len(data) < length:
data += socket.recv(bufsize)
return data
|
A helper method to read of bytes from a socket to a maximum length
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L21-L26
|
[
"def recv(self, bufsize):\n return self.data.pop(0)\n"
] |
"""Transports are used for direct communication with the Riemann server. They
are usually used inside a :py:class:`.Client`, and are used to send and receive
protocol buffer objects."""
from __future__ import absolute_import
import abc
import socket
import ssl
import struct
import riemann_client.riemann_pb2
# Default arguments
HOST = 'localhost'
PORT = 5555
TIMEOUT = None
class RiemannError(Exception):
"""Raised when the Riemann server returns an error message"""
pass
class Transport(object):
"""Abstract transport definition
Subclasses must implement the :py:meth:`.connect`, :py:meth:`.disconnect`
and :py:meth:`.send` methods.
Can be used as a context manager, which will call :py:meth:`.connect` on
entry and :py:meth:`.disconnect` on exit.
"""
__metaclass__ = abc.ABCMeta
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.disconnect()
@abc.abstractmethod
def connect(self):
pass
@abc.abstractmethod
def disconnect(self):
pass
@abc.abstractmethod
def send(self):
pass
class SocketTransport(Transport):
"""Provides common methods for Transports that use a sockets"""
def __init__(self, host=HOST, port=PORT):
self.host = host
self.port = port
@property
def address(self):
"""
:returns: A tuple describing the address to connect to
:rtype: (host, port)
"""
return self.host, self.port
@property
def socket(self):
"""Returns the socket after checking it has been created"""
if not hasattr(self, '_socket'):
raise RuntimeError("Transport has not been connected!")
return self._socket
@socket.setter
def socket(self, value):
self._socket = value
class UDPTransport(SocketTransport):
def connect(self):
"""Creates a UDP socket"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def disconnect(self):
"""Closes the socket"""
self.socket.close()
def send(self, message):
"""Sends a message, but does not return a response
:returns: None - can't receive a response over UDP
"""
self.socket.sendto(message.SerializeToString(), self.address)
return None
class TCPTransport(SocketTransport):
def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT):
"""Communicates with Riemann over TCP
:param str host: The hostname to connect to
:param int port: The port to connect to
:param int timeout: The time in seconds to wait before raising an error
"""
super(TCPTransport, self).__init__(host, port)
self.timeout = timeout
def connect(self):
"""Connects to the given host"""
self.socket = socket.create_connection(self.address, self.timeout)
def disconnect(self):
"""Closes the socket"""
self.socket.close()
def send(self, message):
"""Sends a message to a Riemann server and returns it's response
:param message: The message to send to the Riemann server
:returns: The response message from Riemann
:raises RiemannError: if the server returns an error
"""
message = message.SerializeToString()
self.socket.sendall(struct.pack('!I', len(message)) + message)
length = struct.unpack('!I', self.socket.recv(4))[0]
response = riemann_client.riemann_pb2.Msg()
response.ParseFromString(socket_recvall(self.socket, length))
if not response.ok:
raise RiemannError(response.error)
return response
class TLSTransport(TCPTransport):
def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT, ca_certs=None):
"""Communicates with Riemann over TCP + TLS
Options are the same as :py:class:`.TCPTransport` unless noted
:param str ca_certs: Path to a CA Cert bundle used to create the socket
"""
super(TLSTransport, self).__init__(host, port, timeout)
self.ca_certs = ca_certs
def connect(self):
"""Connects using :py:meth:`TLSTransport.connect` and wraps with TLS"""
super(TLSTransport, self).connect()
self.socket = ssl.wrap_socket(
self.socket,
ssl_version=ssl.PROTOCOL_TLSv1,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_certs)
class BlankTransport(Transport):
"""A transport that collects events in a list, and has no connection
Used by ``--transport none``, which is useful for testing commands without
contacting a Riemann server. This is also used by the automated tests in
``riemann_client/tests/test_riemann_command.py``.
"""
def __init__(self, *args, **kwargs):
self.events = []
def connect(self):
"""Creates a list to hold messages"""
pass
def send(self, message):
"""Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True``
"""
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
return reply
def disconnect(self):
"""Clears the list of messages"""
pass
def __len__(self):
return len(self.events)
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
UDPTransport.send
|
python
|
def send(self, message):
self.socket.sendto(message.SerializeToString(), self.address)
return None
|
Sends a message, but does not return a response
:returns: None - can't receive a response over UDP
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L102-L108
| null |
class UDPTransport(SocketTransport):
def connect(self):
"""Creates a UDP socket"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def disconnect(self):
"""Closes the socket"""
self.socket.close()
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
TCPTransport.connect
|
python
|
def connect(self):
self.socket = socket.create_connection(self.address, self.timeout)
|
Connects to the given host
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L122-L124
| null |
class TCPTransport(SocketTransport):
def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT):
"""Communicates with Riemann over TCP
:param str host: The hostname to connect to
:param int port: The port to connect to
:param int timeout: The time in seconds to wait before raising an error
"""
super(TCPTransport, self).__init__(host, port)
self.timeout = timeout
def disconnect(self):
"""Closes the socket"""
self.socket.close()
def send(self, message):
"""Sends a message to a Riemann server and returns it's response
:param message: The message to send to the Riemann server
:returns: The response message from Riemann
:raises RiemannError: if the server returns an error
"""
message = message.SerializeToString()
self.socket.sendall(struct.pack('!I', len(message)) + message)
length = struct.unpack('!I', self.socket.recv(4))[0]
response = riemann_client.riemann_pb2.Msg()
response.ParseFromString(socket_recvall(self.socket, length))
if not response.ok:
raise RiemannError(response.error)
return response
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
TCPTransport.send
|
python
|
def send(self, message):
message = message.SerializeToString()
self.socket.sendall(struct.pack('!I', len(message)) + message)
length = struct.unpack('!I', self.socket.recv(4))[0]
response = riemann_client.riemann_pb2.Msg()
response.ParseFromString(socket_recvall(self.socket, length))
if not response.ok:
raise RiemannError(response.error)
return response
|
Sends a message to a Riemann server and returns it's response
:param message: The message to send to the Riemann server
:returns: The response message from Riemann
:raises RiemannError: if the server returns an error
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L130-L147
|
[
"def socket_recvall(socket, length, bufsize=4096):\n \"\"\"A helper method to read of bytes from a socket to a maximum length\"\"\"\n data = b\"\"\n while len(data) < length:\n data += socket.recv(bufsize)\n return data\n"
] |
class TCPTransport(SocketTransport):
def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT):
"""Communicates with Riemann over TCP
:param str host: The hostname to connect to
:param int port: The port to connect to
:param int timeout: The time in seconds to wait before raising an error
"""
super(TCPTransport, self).__init__(host, port)
self.timeout = timeout
def connect(self):
"""Connects to the given host"""
self.socket = socket.create_connection(self.address, self.timeout)
def disconnect(self):
"""Closes the socket"""
self.socket.close()
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
TLSTransport.connect
|
python
|
def connect(self):
super(TLSTransport, self).connect()
self.socket = ssl.wrap_socket(
self.socket,
ssl_version=ssl.PROTOCOL_TLSv1,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_certs)
|
Connects using :py:meth:`TLSTransport.connect` and wraps with TLS
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L161-L168
|
[
"def connect(self):\n \"\"\"Connects to the given host\"\"\"\n self.socket = socket.create_connection(self.address, self.timeout)\n"
] |
class TLSTransport(TCPTransport):
def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT, ca_certs=None):
"""Communicates with Riemann over TCP + TLS
Options are the same as :py:class:`.TCPTransport` unless noted
:param str ca_certs: Path to a CA Cert bundle used to create the socket
"""
super(TLSTransport, self).__init__(host, port, timeout)
self.ca_certs = ca_certs
|
borntyping/python-riemann-client
|
riemann_client/transport.py
|
BlankTransport.send
|
python
|
def send(self, message):
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
return reply
|
Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True``
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L186-L195
| null |
class BlankTransport(Transport):
"""A transport that collects events in a list, and has no connection
Used by ``--transport none``, which is useful for testing commands without
contacting a Riemann server. This is also used by the automated tests in
``riemann_client/tests/test_riemann_command.py``.
"""
def __init__(self, *args, **kwargs):
self.events = []
def connect(self):
"""Creates a list to hold messages"""
pass
def disconnect(self):
"""Clears the list of messages"""
pass
def __len__(self):
return len(self.events)
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.create_event
|
python
|
def create_event(data):
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
|
Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L78-L95
| null |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def send_events(self, events):
"""Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def events(self, *events):
"""Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_events(self.create_event(e) for e in events)
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def create_dict(event):
"""Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
"""
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
def query(self, query):
"""Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
"""
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.send_events
|
python
|
def send_events(self, events):
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
|
Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L97-L106
| null |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def create_event(data):
"""Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
"""
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def events(self, *events):
"""Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_events(self.create_event(e) for e in events)
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def create_dict(event):
"""Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
"""
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
def query(self, query):
"""Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
"""
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.events
|
python
|
def events(self, *events):
return self.send_events(self.create_event(e) for e in events)
|
Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L116-L124
|
[
"def send_events(self, events):\n \"\"\"Sends multiple events to Riemann in a single message\n\n :param events: A list or iterable of ``Event`` objects\n :returns: The response message from Riemann\n \"\"\"\n message = riemann_client.riemann_pb2.Msg()\n for event in events:\n message.events.add().MergeFrom(event)\n return self.transport.send(message)\n"
] |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def create_event(data):
"""Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
"""
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
def send_events(self, events):
"""Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def create_dict(event):
"""Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
"""
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
def query(self, query):
"""Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
"""
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.create_dict
|
python
|
def create_dict(event):
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
|
Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L137-L156
| null |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def create_event(data):
"""Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
"""
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
def send_events(self, events):
"""Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def events(self, *events):
"""Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_events(self.create_event(e) for e in events)
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
def query(self, query):
"""Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
"""
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.send_query
|
python
|
def send_query(self, query):
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
|
Sends a query to the Riemann server
:returns: The response message from Riemann
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L158-L165
| null |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def create_event(data):
"""Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
"""
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
def send_events(self, events):
"""Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def events(self, *events):
"""Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_events(self.create_event(e) for e in events)
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def create_dict(event):
"""Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
"""
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
def query(self, query):
"""Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
"""
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
Client.query
|
python
|
def query(self, query):
if isinstance(self.transport, riemann_client.transport.UDPTransport):
raise Exception('Cannot query the Riemann server over UDP')
response = self.send_query(query)
return [self.create_dict(e) for e in response.events]
|
Sends a query to the Riemann server
>>> client.query('true')
:returns: A list of event dictionaries taken from the response
:raises Exception: if used with a :py:class:`.UDPTransport`
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L167-L178
|
[
"def send_query(self, query):\n \"\"\"Sends a query to the Riemann server\n\n :returns: The response message from Riemann\n \"\"\"\n message = riemann_client.riemann_pb2.Msg()\n message.query.string = query\n return self.transport.send(message)\n"
] |
class Client(object):
"""A client for sending events and querying a Riemann server.
Two sets of methods are provided - an API dealing directly with protocol
buffer objects and an extended API that takes and returns dictionaries
representing events.
Protocol buffer API:
- :py:meth:`.send_event`
- :py:meth:`.send_events`
- :py:meth:`.send_query`
Extended API:
- :py:meth:`.event`
- :py:meth:`.events`
- :py:meth:`.query`
Clients do not directly manage connections to a Riemann server - these are
managed by :py:class:`riemann_client.transport.Transport` instances, which
provide methods to read and write messages to the server. Client instances
can be used as a context manager, and will connect and disconnect the
transport when entering and exiting the context.
>>> with Client(transport) as client:
... # Calls transport.connect()
... client.query('true')
... # Calls transport.disconnect()
"""
def __init__(self, transport=None):
if transport is None:
transport = riemann_client.transport.TCPTransport()
self.transport = transport
def __enter__(self):
self.transport.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.transport.disconnect()
@staticmethod
def create_event(data):
"""Translates a dictionary of event attributes to an Event object
:param dict data: The attributes to be set on the event
:returns: A protocol buffer ``Event`` object
"""
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for name, value in data.items():
if value is not None:
setattr(event, name, value)
return event
def send_events(self, events):
"""Sends multiple events to Riemann in a single message
:param events: A list or iterable of ``Event`` objects
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message)
def send_event(self, event):
"""Sends a single event to Riemann
:param event: An ``Event`` protocol buffer object
:returns: The response message from Riemann
"""
return self.send_events((event,))
def events(self, *events):
"""Sends multiple events in a single message
>>> client.events({'service': 'riemann-client', 'state': 'awesome'})
:param \*events: event dictionaries for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_events(self.create_event(e) for e in events)
def event(self, **data):
"""Sends an event, using keyword arguments to create an Event
>>> client.event(service='riemann-client', state='awesome')
:param \*\*data: keyword arguments used for :py:func:`create_event`
:returns: The response message from Riemann
"""
return self.send_event(self.create_event(data))
@staticmethod
def create_dict(event):
"""Translates an Event object to a dictionary of event attributes
All attributes are included, so ``create_dict(create_event(input))``
may return more attributes than were present in the input.
:param event: A protocol buffer ``Event`` object
:returns: A dictionary of event attributes
"""
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = value
return data
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message)
|
borntyping/python-riemann-client
|
riemann_client/client.py
|
QueuedClient.send_events
|
python
|
def send_events(self, events):
for event in events:
self.queue.events.add().MergeFrom(event)
return None
|
Adds multiple events to the queued message
:returns: None - nothing has been sent to the Riemann server yet
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L210-L217
| null |
class QueuedClient(Client):
"""A Riemann client using a queue that can be used to batch send events.
A message object is used as a queue, with the :py:meth:`.send_event` and
:py:meth:`.send_events` methods adding new events to the message and the
:py:meth:`.flush` sending the message.
"""
def __init__(self, transport=None):
super(QueuedClient, self).__init__(transport)
self.clear_queue()
def flush(self):
"""Sends the waiting message to Riemann
:returns: The response message from Riemann
"""
response = self.transport.send(self.queue)
self.clear_queue()
return response
def send_event(self, event):
"""Adds a single event to the queued message
:returns: None - nothing has been sent to the Riemann server yet
"""
self.send_events((event,))
return None
def clear_queue(self):
"""Resets the message/queue to a blank :py:class:`.Msg` object"""
self.queue = riemann_client.riemann_pb2.Msg()
|
borntyping/python-riemann-client
|
riemann_client/command.py
|
echo_event
|
python
|
def echo_event(data):
return click.echo(json.dumps(data, sort_keys=True, indent=2))
|
Echo a json dump of an object using click
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L38-L40
| null |
"""Riemann command line client"""
from __future__ import absolute_import, print_function
import json
import sys
import click
import riemann_client
import riemann_client.client
import riemann_client.transport
__all__ = ['main']
class CommandLineClient(riemann_client.client.Client):
"""Prints to STDERR when an error message is recived from Riemann"""
def __exit__(self, exc_type, exc_value, traceback):
super(CommandLineClient, self).__exit__(exc_type, exc_value, traceback)
if isinstance(exc_type, riemann_client.transport.RiemannError):
click.echo("The server responded with an error: {0}".format(
exc_value.message), file=sys.stderr)
exit(1)
class Pair(click.ParamType):
"""A key value parameter seperated with an '=' symbol"""
name = 'pair'
def convert(self, value, param, ctx):
key, value = value.split('=', 1)
return key.strip(), value.strip()
@click.group()
@click.version_option(version=riemann_client.__version__)
@click.option('--host', '-H', type=click.STRING, default='localhost',
envvar='RIEMANN_HOST', help='Riemann server hostname.')
@click.option('--port', '-P', type=click.INT, default=5555,
envvar='RIEMANN_PORT', help='Riemann server port.')
@click.option('--transport', '-T', 'transport_type', default='tcp',
type=click.Choice(['udp', 'tcp', 'tls', 'none']),
help='The protocol to use to connect to Riemann.')
@click.option('--timeout', '-I', type=click.FLOAT, default=None,
help='Timeout for TCP based connections.')
@click.option('--ca-certs', '-C', type=click.Path(),
help='A CA certificate bundle for TLS connections.')
@click.pass_context
def main(ctx, host, port, transport_type, timeout, ca_certs):
"""Connects to a Riemann server to send events or query the index
By default, will attempt to contact Riemann on localhost:5555 over TCP. The
RIEMANN_HOST and RIEMANN_PORT environment variables can be used to
configure the host and port used. Command line parameters will override the
environment variables.
Use `-T none` to test commands without actually connecting to a server.
"""
if transport_type == 'udp':
if timeout is not None:
ctx.fail('--timeout cannot be used with the UDP transport')
transport = riemann_client.transport.UDPTransport(host, port)
elif transport_type == 'tcp':
transport = riemann_client.transport.TCPTransport(host, port, timeout)
elif transport_type == 'tls':
if ca_certs is None:
ctx.fail('--ca-certs must be set when using the TLS transport')
transport = riemann_client.transport.TLSTransport(
host, port, timeout, ca_certs)
elif transport_type == 'none':
transport = riemann_client.transport.BlankTransport()
ctx.obj = transport
@main.command()
@click.option('-T', '--time', type=click.INT,
help="Event timestamp (unix format)")
@click.option('-S', '--state', type=click.STRING,
help="Event state")
@click.option('-s', '--service', type=click.STRING,
help="Event service name")
@click.option('-h', '--host', type=click.STRING,
help="Event hostname (uses system's by default)")
@click.option('-d', '--description', type=click.STRING,
help="Event description")
@click.option('-t', '--tag', type=click.STRING, multiple=True,
help="Event tag (multiple)")
@click.option('-l', '--ttl', type=click.FLOAT,
help="Event time to live in seconds")
@click.option('-a', '--attr', '--attribute', type=Pair(), multiple=True,
help="Event attribute (key=value, multiple)")
@click.option('-m', '--metric', '--metric_f', type=click.FLOAT,
help="Event metric (uses metric_f)")
@click.option('--echo/--no-echo', default=True,
help="Echo event object after sending")
@click.pass_obj
def send(transport, time, state, host, description, service, tag, attribute,
ttl, metric_f, echo):
"""Send a single event to Riemann"""
client = CommandLineClient(transport)
event = client.create_event({
'time': time,
'state': state,
'host': host,
'description': description,
'service': service,
'tags': tag,
'attributes': dict(attribute),
'ttl': ttl,
'metric_f': metric_f
})
with client:
client.send_event(event)
if echo:
echo_event(client.create_dict(event))
@main.command()
@click.argument('query', 'query')
@click.pass_obj
def query(transport, query):
"""Query the Riemann server"""
with CommandLineClient(transport) as client:
echo_event(client.query(query))
|
borntyping/python-riemann-client
|
riemann_client/command.py
|
main
|
python
|
def main(ctx, host, port, transport_type, timeout, ca_certs):
if transport_type == 'udp':
if timeout is not None:
ctx.fail('--timeout cannot be used with the UDP transport')
transport = riemann_client.transport.UDPTransport(host, port)
elif transport_type == 'tcp':
transport = riemann_client.transport.TCPTransport(host, port, timeout)
elif transport_type == 'tls':
if ca_certs is None:
ctx.fail('--ca-certs must be set when using the TLS transport')
transport = riemann_client.transport.TLSTransport(
host, port, timeout, ca_certs)
elif transport_type == 'none':
transport = riemann_client.transport.BlankTransport()
ctx.obj = transport
|
Connects to a Riemann server to send events or query the index
By default, will attempt to contact Riemann on localhost:5555 over TCP. The
RIEMANN_HOST and RIEMANN_PORT environment variables can be used to
configure the host and port used. Command line parameters will override the
environment variables.
Use `-T none` to test commands without actually connecting to a server.
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L57-L81
| null |
"""Riemann command line client"""
from __future__ import absolute_import, print_function
import json
import sys
import click
import riemann_client
import riemann_client.client
import riemann_client.transport
__all__ = ['main']
class CommandLineClient(riemann_client.client.Client):
"""Prints to STDERR when an error message is recived from Riemann"""
def __exit__(self, exc_type, exc_value, traceback):
super(CommandLineClient, self).__exit__(exc_type, exc_value, traceback)
if isinstance(exc_type, riemann_client.transport.RiemannError):
click.echo("The server responded with an error: {0}".format(
exc_value.message), file=sys.stderr)
exit(1)
class Pair(click.ParamType):
"""A key value parameter seperated with an '=' symbol"""
name = 'pair'
def convert(self, value, param, ctx):
key, value = value.split('=', 1)
return key.strip(), value.strip()
def echo_event(data):
"""Echo a json dump of an object using click"""
return click.echo(json.dumps(data, sort_keys=True, indent=2))
@click.group()
@click.version_option(version=riemann_client.__version__)
@click.option('--host', '-H', type=click.STRING, default='localhost',
envvar='RIEMANN_HOST', help='Riemann server hostname.')
@click.option('--port', '-P', type=click.INT, default=5555,
envvar='RIEMANN_PORT', help='Riemann server port.')
@click.option('--transport', '-T', 'transport_type', default='tcp',
type=click.Choice(['udp', 'tcp', 'tls', 'none']),
help='The protocol to use to connect to Riemann.')
@click.option('--timeout', '-I', type=click.FLOAT, default=None,
help='Timeout for TCP based connections.')
@click.option('--ca-certs', '-C', type=click.Path(),
help='A CA certificate bundle for TLS connections.')
@click.pass_context
@main.command()
@click.option('-T', '--time', type=click.INT,
help="Event timestamp (unix format)")
@click.option('-S', '--state', type=click.STRING,
help="Event state")
@click.option('-s', '--service', type=click.STRING,
help="Event service name")
@click.option('-h', '--host', type=click.STRING,
help="Event hostname (uses system's by default)")
@click.option('-d', '--description', type=click.STRING,
help="Event description")
@click.option('-t', '--tag', type=click.STRING, multiple=True,
help="Event tag (multiple)")
@click.option('-l', '--ttl', type=click.FLOAT,
help="Event time to live in seconds")
@click.option('-a', '--attr', '--attribute', type=Pair(), multiple=True,
help="Event attribute (key=value, multiple)")
@click.option('-m', '--metric', '--metric_f', type=click.FLOAT,
help="Event metric (uses metric_f)")
@click.option('--echo/--no-echo', default=True,
help="Echo event object after sending")
@click.pass_obj
def send(transport, time, state, host, description, service, tag, attribute,
ttl, metric_f, echo):
"""Send a single event to Riemann"""
client = CommandLineClient(transport)
event = client.create_event({
'time': time,
'state': state,
'host': host,
'description': description,
'service': service,
'tags': tag,
'attributes': dict(attribute),
'ttl': ttl,
'metric_f': metric_f
})
with client:
client.send_event(event)
if echo:
echo_event(client.create_dict(event))
@main.command()
@click.argument('query', 'query')
@click.pass_obj
def query(transport, query):
"""Query the Riemann server"""
with CommandLineClient(transport) as client:
echo_event(client.query(query))
|
borntyping/python-riemann-client
|
riemann_client/command.py
|
send
|
python
|
def send(transport, time, state, host, description, service, tag, attribute,
ttl, metric_f, echo):
client = CommandLineClient(transport)
event = client.create_event({
'time': time,
'state': state,
'host': host,
'description': description,
'service': service,
'tags': tag,
'attributes': dict(attribute),
'ttl': ttl,
'metric_f': metric_f
})
with client:
client.send_event(event)
if echo:
echo_event(client.create_dict(event))
|
Send a single event to Riemann
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L106-L125
|
[
"def echo_event(data):\n \"\"\"Echo a json dump of an object using click\"\"\"\n return click.echo(json.dumps(data, sort_keys=True, indent=2))\n",
"def create_event(data):\n \"\"\"Translates a dictionary of event attributes to an Event object\n\n :param dict data: The attributes to be set on the event\n :returns: A protocol buffer ``Event`` object\n \"\"\"\n event = riemann_client.riemann_pb2.Event()\n event.host = socket.gethostname()\n event.tags.extend(data.pop('tags', []))\n\n for key, value in data.pop('attributes', {}).items():\n attribute = event.attributes.add()\n attribute.key, attribute.value = key, value\n\n for name, value in data.items():\n if value is not None:\n setattr(event, name, value)\n return event\n",
"def send_event(self, event):\n \"\"\"Sends a single event to Riemann\n\n :param event: An ``Event`` protocol buffer object\n :returns: The response message from Riemann\n \"\"\"\n return self.send_events((event,))\n",
"def create_dict(event):\n \"\"\"Translates an Event object to a dictionary of event attributes\n\n All attributes are included, so ``create_dict(create_event(input))``\n may return more attributes than were present in the input.\n\n :param event: A protocol buffer ``Event`` object\n :returns: A dictionary of event attributes\n \"\"\"\n\n data = dict()\n\n for descriptor, value in event.ListFields():\n if descriptor.name == 'tags':\n value = list(value)\n elif descriptor.name == 'attributes':\n value = dict(((a.key, a.value) for a in value))\n data[descriptor.name] = value\n\n return data\n"
] |
"""Riemann command line client"""
from __future__ import absolute_import, print_function
import json
import sys
import click
import riemann_client
import riemann_client.client
import riemann_client.transport
__all__ = ['main']
class CommandLineClient(riemann_client.client.Client):
"""Prints to STDERR when an error message is recived from Riemann"""
def __exit__(self, exc_type, exc_value, traceback):
super(CommandLineClient, self).__exit__(exc_type, exc_value, traceback)
if isinstance(exc_type, riemann_client.transport.RiemannError):
click.echo("The server responded with an error: {0}".format(
exc_value.message), file=sys.stderr)
exit(1)
class Pair(click.ParamType):
"""A key value parameter seperated with an '=' symbol"""
name = 'pair'
def convert(self, value, param, ctx):
key, value = value.split('=', 1)
return key.strip(), value.strip()
def echo_event(data):
"""Echo a json dump of an object using click"""
return click.echo(json.dumps(data, sort_keys=True, indent=2))
@click.group()
@click.version_option(version=riemann_client.__version__)
@click.option('--host', '-H', type=click.STRING, default='localhost',
envvar='RIEMANN_HOST', help='Riemann server hostname.')
@click.option('--port', '-P', type=click.INT, default=5555,
envvar='RIEMANN_PORT', help='Riemann server port.')
@click.option('--transport', '-T', 'transport_type', default='tcp',
type=click.Choice(['udp', 'tcp', 'tls', 'none']),
help='The protocol to use to connect to Riemann.')
@click.option('--timeout', '-I', type=click.FLOAT, default=None,
help='Timeout for TCP based connections.')
@click.option('--ca-certs', '-C', type=click.Path(),
help='A CA certificate bundle for TLS connections.')
@click.pass_context
def main(ctx, host, port, transport_type, timeout, ca_certs):
"""Connects to a Riemann server to send events or query the index
By default, will attempt to contact Riemann on localhost:5555 over TCP. The
RIEMANN_HOST and RIEMANN_PORT environment variables can be used to
configure the host and port used. Command line parameters will override the
environment variables.
Use `-T none` to test commands without actually connecting to a server.
"""
if transport_type == 'udp':
if timeout is not None:
ctx.fail('--timeout cannot be used with the UDP transport')
transport = riemann_client.transport.UDPTransport(host, port)
elif transport_type == 'tcp':
transport = riemann_client.transport.TCPTransport(host, port, timeout)
elif transport_type == 'tls':
if ca_certs is None:
ctx.fail('--ca-certs must be set when using the TLS transport')
transport = riemann_client.transport.TLSTransport(
host, port, timeout, ca_certs)
elif transport_type == 'none':
transport = riemann_client.transport.BlankTransport()
ctx.obj = transport
@main.command()
@click.option('-T', '--time', type=click.INT,
help="Event timestamp (unix format)")
@click.option('-S', '--state', type=click.STRING,
help="Event state")
@click.option('-s', '--service', type=click.STRING,
help="Event service name")
@click.option('-h', '--host', type=click.STRING,
help="Event hostname (uses system's by default)")
@click.option('-d', '--description', type=click.STRING,
help="Event description")
@click.option('-t', '--tag', type=click.STRING, multiple=True,
help="Event tag (multiple)")
@click.option('-l', '--ttl', type=click.FLOAT,
help="Event time to live in seconds")
@click.option('-a', '--attr', '--attribute', type=Pair(), multiple=True,
help="Event attribute (key=value, multiple)")
@click.option('-m', '--metric', '--metric_f', type=click.FLOAT,
help="Event metric (uses metric_f)")
@click.option('--echo/--no-echo', default=True,
help="Echo event object after sending")
@click.pass_obj
@main.command()
@click.argument('query', 'query')
@click.pass_obj
def query(transport, query):
"""Query the Riemann server"""
with CommandLineClient(transport) as client:
echo_event(client.query(query))
|
borntyping/python-riemann-client
|
riemann_client/command.py
|
query
|
python
|
def query(transport, query):
with CommandLineClient(transport) as client:
echo_event(client.query(query))
|
Query the Riemann server
|
train
|
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L131-L134
|
[
"def echo_event(data):\n \"\"\"Echo a json dump of an object using click\"\"\"\n return click.echo(json.dumps(data, sort_keys=True, indent=2))\n"
] |
"""Riemann command line client"""
from __future__ import absolute_import, print_function
import json
import sys
import click
import riemann_client
import riemann_client.client
import riemann_client.transport
__all__ = ['main']
class CommandLineClient(riemann_client.client.Client):
"""Prints to STDERR when an error message is recived from Riemann"""
def __exit__(self, exc_type, exc_value, traceback):
super(CommandLineClient, self).__exit__(exc_type, exc_value, traceback)
if isinstance(exc_type, riemann_client.transport.RiemannError):
click.echo("The server responded with an error: {0}".format(
exc_value.message), file=sys.stderr)
exit(1)
class Pair(click.ParamType):
"""A key value parameter seperated with an '=' symbol"""
name = 'pair'
def convert(self, value, param, ctx):
key, value = value.split('=', 1)
return key.strip(), value.strip()
def echo_event(data):
"""Echo a json dump of an object using click"""
return click.echo(json.dumps(data, sort_keys=True, indent=2))
@click.group()
@click.version_option(version=riemann_client.__version__)
@click.option('--host', '-H', type=click.STRING, default='localhost',
envvar='RIEMANN_HOST', help='Riemann server hostname.')
@click.option('--port', '-P', type=click.INT, default=5555,
envvar='RIEMANN_PORT', help='Riemann server port.')
@click.option('--transport', '-T', 'transport_type', default='tcp',
type=click.Choice(['udp', 'tcp', 'tls', 'none']),
help='The protocol to use to connect to Riemann.')
@click.option('--timeout', '-I', type=click.FLOAT, default=None,
help='Timeout for TCP based connections.')
@click.option('--ca-certs', '-C', type=click.Path(),
help='A CA certificate bundle for TLS connections.')
@click.pass_context
def main(ctx, host, port, transport_type, timeout, ca_certs):
"""Connects to a Riemann server to send events or query the index
By default, will attempt to contact Riemann on localhost:5555 over TCP. The
RIEMANN_HOST and RIEMANN_PORT environment variables can be used to
configure the host and port used. Command line parameters will override the
environment variables.
Use `-T none` to test commands without actually connecting to a server.
"""
if transport_type == 'udp':
if timeout is not None:
ctx.fail('--timeout cannot be used with the UDP transport')
transport = riemann_client.transport.UDPTransport(host, port)
elif transport_type == 'tcp':
transport = riemann_client.transport.TCPTransport(host, port, timeout)
elif transport_type == 'tls':
if ca_certs is None:
ctx.fail('--ca-certs must be set when using the TLS transport')
transport = riemann_client.transport.TLSTransport(
host, port, timeout, ca_certs)
elif transport_type == 'none':
transport = riemann_client.transport.BlankTransport()
ctx.obj = transport
@main.command()
@click.option('-T', '--time', type=click.INT,
help="Event timestamp (unix format)")
@click.option('-S', '--state', type=click.STRING,
help="Event state")
@click.option('-s', '--service', type=click.STRING,
help="Event service name")
@click.option('-h', '--host', type=click.STRING,
help="Event hostname (uses system's by default)")
@click.option('-d', '--description', type=click.STRING,
help="Event description")
@click.option('-t', '--tag', type=click.STRING, multiple=True,
help="Event tag (multiple)")
@click.option('-l', '--ttl', type=click.FLOAT,
help="Event time to live in seconds")
@click.option('-a', '--attr', '--attribute', type=Pair(), multiple=True,
help="Event attribute (key=value, multiple)")
@click.option('-m', '--metric', '--metric_f', type=click.FLOAT,
help="Event metric (uses metric_f)")
@click.option('--echo/--no-echo', default=True,
help="Echo event object after sending")
@click.pass_obj
def send(transport, time, state, host, description, service, tag, attribute,
ttl, metric_f, echo):
"""Send a single event to Riemann"""
client = CommandLineClient(transport)
event = client.create_event({
'time': time,
'state': state,
'host': host,
'description': description,
'service': service,
'tags': tag,
'attributes': dict(attribute),
'ttl': ttl,
'metric_f': metric_f
})
with client:
client.send_event(event)
if echo:
echo_event(client.create_dict(event))
@main.command()
@click.argument('query', 'query')
@click.pass_obj
|
mishbahr/django-connected
|
connected_accounts/admin.py
|
AccountAdmin.get_urls
|
python
|
def get_urls(self):
urls = super(AccountAdmin, self).get_urls()
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.opts.app_label, self.opts.model_name
extra_urls = [
url(r'^login/(?P<provider>(\w|-)+)/$',
wrap(OAuthRedirect.as_view()), name='%s_%s_login' % info),
url(r'^callback/(?P<provider>(\w|-)+)/$',
wrap(OAuthCallback.as_view()), name='%s_%s_callback' % info),
url(r'^(.+)/json/$', wrap(self.json_view), name='%s_%s_json' % info),
]
return extra_urls + urls
|
Add the export view to urls.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/admin.py#L71-L92
|
[
"def wrap(view):\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\n"
] |
class AccountAdmin(admin.ModelAdmin):
actions = None
change_form_template = 'admin/connected_accounts/account/change_form.html'
readonly_fields = ('avatar', 'uid', 'provider', 'profile_url',
'oauth_token', 'oauth_token_secret', 'user',
'expires_at', 'date_added', 'last_login', )
list_display = ('avatar', '__str__', 'provider', )
list_display_links = ('__str__', )
fieldsets = (
(None, {
'fields': ('avatar', 'provider', 'uid', 'profile_url', )
}),
(None, {
'fields': ('oauth_token', 'oauth_token_secret', )
}),
(None, {
'fields': ('date_added', 'last_login', 'expires_at', 'user', )
}),
)
class Media:
css = {
'all': (
'css/connected_accounts/admin/connected_accounts.css',
)
}
def add_view(self, request, form_url='', extra_context=None):
if not self.has_add_permission(request):
raise PermissionDenied
data = None
changelist_filters = request.GET.get('_changelist_filters')
if request.method == 'GET' and changelist_filters is not None:
changelist_filters = dict(parse_qsl(changelist_filters))
if 'provider' in changelist_filters:
data = {
'provider': changelist_filters['provider']
}
form = AccountCreationForm(data=request.POST if request.method == 'POST' else data)
if form.is_valid():
info = self.model._meta.app_label, self.model._meta.model_name
preserved_filters = self.get_preserved_filters(request)
request.session[PRESERVED_FILTERS_SESSION_KEY] = preserved_filters
redirect_url = reverse('admin:%s_%s_login' % info,
kwargs={'provider': form.cleaned_data['provider']})
return redirect(redirect_url)
fieldsets = (
(None, {
'fields': ('provider', )
}),
)
adminForm = helpers.AdminForm(form, list(fieldsets), {}, model_admin=self)
media = self.media + adminForm.media
context = dict(
adminform=adminForm,
is_popup=IS_POPUP_VAR in request.GET,
media=media,
errors=helpers.AdminErrorList(form, ()),
preserved_filters=self.get_preserved_filters(request),
)
context.update(extra_context or {})
return self.render_change_form(request, context, add=True, change=False, form_url=form_url)
def json_view(self, request, object_id):
obj = self.get_object(request, unquote(object_id))
return HttpResponse(content=obj.to_json(), content_type='application/json')
def response_change(self, request, obj):
opts = self.model._meta
preserved_filters = self.get_preserved_filters(request)
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
if '_reset_data' in request.POST:
if obj.is_expired:
obj.refresh_access_token()
provider = obj.get_provider()
profile_data = provider.get_profile_data(obj.raw_token)
if profile_data is None:
msg = _('Could not retrieve profile data for the %(name)s "%(obj)s" ') % msg_dict
self.message_user(request, msg, messages.ERROR)
else:
obj.extra_data = provider.extract_extra_data(profile_data)
obj.save()
msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
self.message_user(request, msg, messages.SUCCESS)
redirect_url = request.path
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
return super(AccountAdmin, self).response_change(request, obj)
def avatar(self, obj):
return render_to_string(
'admin/connected_accounts/account/includes/changelist_avatar.html', {
'avatar_url': obj.get_avatar_url(),
})
avatar.allow_tags = True
avatar.short_description = _('Avatar')
def profile_url(self, obj):
if obj.get_profile_url():
return '<a href="{0}" target="_blank">{0}</a>'.format(obj.get_profile_url())
return '—'
profile_url.allow_tags = True
profile_url.short_description = _('Profile URL')
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
BaseOAuthProvider.get_profile_data
|
python
|
def get_profile_data(self, raw_token):
try:
response = self.request('get', self.profile_url, token=raw_token)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch user profile: {0}'.format(e))
return None
else:
return response.json() or response.text
|
Fetch user profile information.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L73-L82
|
[
"def request(self, method, url, **kwargs):\n \"\"\"Build remote url request.\"\"\"\n return request(method, url, **kwargs)\n"
] |
class BaseOAuthProvider(object):
id = ''
name = ''
account_class = ProviderAccount
authorization_url = ''
access_token_url = ''
profile_url = ''
consumer_key = ''
consumer_secret = ''
scope = []
scope_separator = ' '
def __init__(self, token=''):
self.token = token
def wrap_account(self, account):
return self.account_class(account, self)
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def refresh_access_token(self, raw_token):
"""Refreshing an OAuth2 token using a refresh token."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def get_redirect_url(self, request, callback, parameters=None):
"""Build authentication redirect url."""
args = self.get_redirect_args(request, callback=callback)
additional = parameters or {}
args.update(additional)
params = urlencode(args)
return '{0}?{1}'.format(self.authorization_url, params)
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def request(self, method, url, **kwargs):
"""Build remote url request."""
return request(method, url, **kwargs)
def extract_uid(self, data):
"""Return unique identifier from the profile info."""
return data.get('id', None)
def get_scope(self, request):
dynamic_scope = request.GET.get('scope', None)
if dynamic_scope:
self.scope.extend(dynamic_scope.split(','))
return self.scope
def extract_extra_data(self, data):
return data
@property
def session_key(self):
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
@property
def is_enabled(self):
return self.consumer_key is not None and self.consumer_secret is not None
def to_str(self):
return force_text(self.name)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
BaseOAuthProvider.get_redirect_url
|
python
|
def get_redirect_url(self, request, callback, parameters=None):
args = self.get_redirect_args(request, callback=callback)
additional = parameters or {}
args.update(additional)
params = urlencode(args)
return '{0}?{1}'.format(self.authorization_url, params)
|
Build authentication redirect url.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L88-L94
|
[
"def get_redirect_args(self, request, callback):\n \"\"\"Get request parameters for redirect url.\"\"\"\n raise NotImplementedError('Defined in a sub-class') # pragma: no cover\n"
] |
class BaseOAuthProvider(object):
id = ''
name = ''
account_class = ProviderAccount
authorization_url = ''
access_token_url = ''
profile_url = ''
consumer_key = ''
consumer_secret = ''
scope = []
scope_separator = ' '
def __init__(self, token=''):
self.token = token
def wrap_account(self, account):
return self.account_class(account, self)
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def refresh_access_token(self, raw_token):
"""Refreshing an OAuth2 token using a refresh token."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def get_profile_data(self, raw_token):
"""Fetch user profile information."""
try:
response = self.request('get', self.profile_url, token=raw_token)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch user profile: {0}'.format(e))
return None
else:
return response.json() or response.text
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
def request(self, method, url, **kwargs):
"""Build remote url request."""
return request(method, url, **kwargs)
def extract_uid(self, data):
"""Return unique identifier from the profile info."""
return data.get('id', None)
def get_scope(self, request):
dynamic_scope = request.GET.get('scope', None)
if dynamic_scope:
self.scope.extend(dynamic_scope.split(','))
return self.scope
def extract_extra_data(self, data):
return data
@property
def session_key(self):
raise NotImplementedError('Defined in a sub-class') # pragma: no cover
@property
def is_enabled(self):
return self.consumer_key is not None and self.consumer_secret is not None
def to_str(self):
return force_text(self.name)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuthProvider.get_request_token
|
python
|
def get_request_token(self, request, callback):
callback = force_text(request.build_absolute_uri(callback))
try:
response = self.request('post', self.request_token_url, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch request token: {0}'.format(e))
return None
else:
return response.text
|
Fetch the OAuth request token. Only required for OAuth 1.0.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L152-L162
|
[
"def request(self, method, url, **kwargs):\n \"\"\"Build remote url request. Constructs necessary auth.\"\"\"\n user_token = kwargs.pop('token', self.token)\n token, secret, _ = self.parse_raw_token(user_token)\n callback = kwargs.pop('oauth_callback', None)\n verifier = kwargs.get('data', {}).pop('oauth_verifier', None)\n oauth = OAuth1(\n resource_owner_key=token,\n resource_owner_secret=secret,\n client_key=self.consumer_key,\n client_secret=self.consumer_secret,\n verifier=verifier,\n callback_uri=callback,\n )\n kwargs['auth'] = oauth\n return super(OAuthProvider, self).request(method, url, **kwargs)\n"
] |
class OAuthProvider(BaseOAuthProvider):
request_token_url = ''
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
raw_token = request.session.get(self.session_key, None)
verifier = request.GET.get('oauth_verifier', None)
if raw_token is not None and verifier is not None:
data = {'oauth_verifier': verifier}
callback = request.build_absolute_uri(callback or request.path)
callback = force_text(callback)
try:
response = self.request(
'post', self.access_token_url,
token=raw_token, data=data, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
return None
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret, _ = self.parse_raw_token(raw_token)
if token is not None and secret is not None:
request.session[self.session_key] = raw_token
args = {
'oauth_token': token,
'oauth_callback': callback,
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
return args
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
qs = parse_qs(raw_token)
token = qs.get('oauth_token', [None])[0]
token_secret = qs.get('oauth_token_secret', [None])[0]
return (token, token_secret, None)
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, _ = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(
resource_owner_key=token,
resource_owner_secret=secret,
client_key=self.consumer_key,
client_secret=self.consumer_secret,
verifier=verifier,
callback_uri=callback,
)
kwargs['auth'] = oauth
return super(OAuthProvider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-request-token'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuthProvider.get_redirect_args
|
python
|
def get_redirect_args(self, request, callback):
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret, _ = self.parse_raw_token(raw_token)
if token is not None and secret is not None:
request.session[self.session_key] = raw_token
args = {
'oauth_token': token,
'oauth_callback': callback,
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
return args
|
Get request parameters for redirect url.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L164-L180
|
[
"def get_scope(self, request):\n dynamic_scope = request.GET.get('scope', None)\n if dynamic_scope:\n self.scope.extend(dynamic_scope.split(','))\n return self.scope\n",
"def get_request_token(self, request, callback):\n \"\"\"Fetch the OAuth request token. Only required for OAuth 1.0.\"\"\"\n callback = force_text(request.build_absolute_uri(callback))\n try:\n response = self.request('post', self.request_token_url, oauth_callback=callback)\n response.raise_for_status()\n except RequestException as e:\n logger.error('Unable to fetch request token: {0}'.format(e))\n return None\n else:\n return response.text\n",
"def parse_raw_token(self, raw_token):\n \"\"\"Parse token and secret from raw token response.\"\"\"\n if raw_token is None:\n return (None, None, None)\n qs = parse_qs(raw_token)\n token = qs.get('oauth_token', [None])[0]\n token_secret = qs.get('oauth_token_secret', [None])[0]\n return (token, token_secret, None)\n"
] |
class OAuthProvider(BaseOAuthProvider):
request_token_url = ''
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
raw_token = request.session.get(self.session_key, None)
verifier = request.GET.get('oauth_verifier', None)
if raw_token is not None and verifier is not None:
data = {'oauth_verifier': verifier}
callback = request.build_absolute_uri(callback or request.path)
callback = force_text(callback)
try:
response = self.request(
'post', self.access_token_url,
token=raw_token, data=data, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
return None
def get_request_token(self, request, callback):
"""Fetch the OAuth request token. Only required for OAuth 1.0."""
callback = force_text(request.build_absolute_uri(callback))
try:
response = self.request('post', self.request_token_url, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch request token: {0}'.format(e))
return None
else:
return response.text
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
qs = parse_qs(raw_token)
token = qs.get('oauth_token', [None])[0]
token_secret = qs.get('oauth_token_secret', [None])[0]
return (token, token_secret, None)
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, _ = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(
resource_owner_key=token,
resource_owner_secret=secret,
client_key=self.consumer_key,
client_secret=self.consumer_secret,
verifier=verifier,
callback_uri=callback,
)
kwargs['auth'] = oauth
return super(OAuthProvider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-request-token'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuthProvider.parse_raw_token
|
python
|
def parse_raw_token(self, raw_token):
if raw_token is None:
return (None, None, None)
qs = parse_qs(raw_token)
token = qs.get('oauth_token', [None])[0]
token_secret = qs.get('oauth_token_secret', [None])[0]
return (token, token_secret, None)
|
Parse token and secret from raw token response.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L182-L189
| null |
class OAuthProvider(BaseOAuthProvider):
request_token_url = ''
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
raw_token = request.session.get(self.session_key, None)
verifier = request.GET.get('oauth_verifier', None)
if raw_token is not None and verifier is not None:
data = {'oauth_verifier': verifier}
callback = request.build_absolute_uri(callback or request.path)
callback = force_text(callback)
try:
response = self.request(
'post', self.access_token_url,
token=raw_token, data=data, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
return None
def get_request_token(self, request, callback):
"""Fetch the OAuth request token. Only required for OAuth 1.0."""
callback = force_text(request.build_absolute_uri(callback))
try:
response = self.request('post', self.request_token_url, oauth_callback=callback)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch request token: {0}'.format(e))
return None
else:
return response.text
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret, _ = self.parse_raw_token(raw_token)
if token is not None and secret is not None:
request.session[self.session_key] = raw_token
args = {
'oauth_token': token,
'oauth_callback': callback,
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
return args
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, _ = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(
resource_owner_key=token,
resource_owner_secret=secret,
client_key=self.consumer_key,
client_secret=self.consumer_secret,
verifier=verifier,
callback_uri=callback,
)
kwargs['auth'] = oauth
return super(OAuthProvider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-request-token'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuth2Provider.get_access_token
|
python
|
def get_access_token(self, request, callback=None):
callback = request.build_absolute_uri(callback or request.path)
if not self.check_application_state(request):
logger.error('Application state check failed.')
return None
if 'code' in request.GET:
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'client_secret': self.consumer_secret,
'code': request.GET['code'],
'grant_type': 'authorization_code',
}
else:
logger.error('No code returned by the provider')
return None
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
|
Fetch access token from callback request.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L232-L256
|
[
"def check_application_state(self, request):\n \"\"\"Check optional state parameter.\"\"\"\n stored = request.session.get(self.session_key, None)\n returned = request.GET.get('state', None)\n check = False\n if stored is not None:\n if returned is not None:\n check = constant_time_compare(stored, returned)\n else:\n logger.error('No state parameter returned by the provider.')\n else:\n logger.error('No state stored in the sesssion.')\n return check\n"
] |
class OAuth2Provider(BaseOAuthProvider):
supports_state = True
expires_in_key = 'expires_in'
auth_params = {}
def check_application_state(self, request):
"""Check optional state parameter."""
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check = constant_time_compare(stored, returned)
else:
logger.error('No state parameter returned by the provider.')
else:
logger.error('No state stored in the sesssion.')
return check
def refresh_access_token(self, raw_token, **kwargs):
token, refresh_token, expires_at = self.parse_raw_token(raw_token)
refresh_token = kwargs.pop('refresh_token', refresh_token)
args = {
'client_id': self.consumer_key,
'client_secret': self.consumer_secret,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
}
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def get_application_state(self, request, callback):
"""Generate state optional parameter."""
return get_random_string(32)
def get_auth_params(self, request, action=None):
return self.auth_params
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
state = self.get_application_state(request, callback)
if state is not None:
args['state'] = state
request.session[self.session_key] = state
auth_params = self.get_auth_params(request)
if auth_params:
args.update(auth_params)
return args
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = parse_qs(raw_token)
token = qs.get('access_token', [None])[0]
refresh_token = qs.get('refresh_token', [None])[0]
expires_at = qs.get(self.expires_in_key, [None])[0]
else:
token = token_data.get('access_token', None)
refresh_token = token_data.get('refresh_token', None)
expires_at = token_data.get(self.expires_in_key, None)
if expires_at:
expires_at = timezone.now() + timedelta(seconds=int(expires_at))
return (token, refresh_token, expires_at)
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, expires_at = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] = token
kwargs['params'] = params
return super(OAuth2Provider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-application-state'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuth2Provider.get_redirect_args
|
python
|
def get_redirect_args(self, request, callback):
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
state = self.get_application_state(request, callback)
if state is not None:
args['state'] = state
request.session[self.session_key] = state
auth_params = self.get_auth_params(request)
if auth_params:
args.update(auth_params)
return args
|
Get request parameters for redirect url.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L285-L307
|
[
"def get_scope(self, request):\n dynamic_scope = request.GET.get('scope', None)\n if dynamic_scope:\n self.scope.extend(dynamic_scope.split(','))\n return self.scope\n",
"def get_application_state(self, request, callback):\n \"\"\"Generate state optional parameter.\"\"\"\n return get_random_string(32)\n",
"def get_auth_params(self, request, action=None):\n return self.auth_params\n"
] |
class OAuth2Provider(BaseOAuthProvider):
supports_state = True
expires_in_key = 'expires_in'
auth_params = {}
def check_application_state(self, request):
"""Check optional state parameter."""
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check = constant_time_compare(stored, returned)
else:
logger.error('No state parameter returned by the provider.')
else:
logger.error('No state stored in the sesssion.')
return check
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
callback = request.build_absolute_uri(callback or request.path)
if not self.check_application_state(request):
logger.error('Application state check failed.')
return None
if 'code' in request.GET:
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'client_secret': self.consumer_secret,
'code': request.GET['code'],
'grant_type': 'authorization_code',
}
else:
logger.error('No code returned by the provider')
return None
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def refresh_access_token(self, raw_token, **kwargs):
token, refresh_token, expires_at = self.parse_raw_token(raw_token)
refresh_token = kwargs.pop('refresh_token', refresh_token)
args = {
'client_id': self.consumer_key,
'client_secret': self.consumer_secret,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
}
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def get_application_state(self, request, callback):
"""Generate state optional parameter."""
return get_random_string(32)
def get_auth_params(self, request, action=None):
return self.auth_params
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = parse_qs(raw_token)
token = qs.get('access_token', [None])[0]
refresh_token = qs.get('refresh_token', [None])[0]
expires_at = qs.get(self.expires_in_key, [None])[0]
else:
token = token_data.get('access_token', None)
refresh_token = token_data.get('refresh_token', None)
expires_at = token_data.get(self.expires_in_key, None)
if expires_at:
expires_at = timezone.now() + timedelta(seconds=int(expires_at))
return (token, refresh_token, expires_at)
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, expires_at = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] = token
kwargs['params'] = params
return super(OAuth2Provider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-application-state'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuth2Provider.parse_raw_token
|
python
|
def parse_raw_token(self, raw_token):
if raw_token is None:
return (None, None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = parse_qs(raw_token)
token = qs.get('access_token', [None])[0]
refresh_token = qs.get('refresh_token', [None])[0]
expires_at = qs.get(self.expires_in_key, [None])[0]
else:
token = token_data.get('access_token', None)
refresh_token = token_data.get('refresh_token', None)
expires_at = token_data.get(self.expires_in_key, None)
if expires_at:
expires_at = timezone.now() + timedelta(seconds=int(expires_at))
return (token, refresh_token, expires_at)
|
Parse token and secret from raw token response.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L309-L329
| null |
class OAuth2Provider(BaseOAuthProvider):
supports_state = True
expires_in_key = 'expires_in'
auth_params = {}
def check_application_state(self, request):
"""Check optional state parameter."""
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check = constant_time_compare(stored, returned)
else:
logger.error('No state parameter returned by the provider.')
else:
logger.error('No state stored in the sesssion.')
return check
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
callback = request.build_absolute_uri(callback or request.path)
if not self.check_application_state(request):
logger.error('Application state check failed.')
return None
if 'code' in request.GET:
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'client_secret': self.consumer_secret,
'code': request.GET['code'],
'grant_type': 'authorization_code',
}
else:
logger.error('No code returned by the provider')
return None
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def refresh_access_token(self, raw_token, **kwargs):
token, refresh_token, expires_at = self.parse_raw_token(raw_token)
refresh_token = kwargs.pop('refresh_token', refresh_token)
args = {
'client_id': self.consumer_key,
'client_secret': self.consumer_secret,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
}
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def get_application_state(self, request, callback):
"""Generate state optional parameter."""
return get_random_string(32)
def get_auth_params(self, request, action=None):
return self.auth_params
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
state = self.get_application_state(request, callback)
if state is not None:
args['state'] = state
request.session[self.session_key] = state
auth_params = self.get_auth_params(request)
if auth_params:
args.update(auth_params)
return args
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, expires_at = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] = token
kwargs['params'] = params
return super(OAuth2Provider, self).request(method, url, **kwargs)
@property
def session_key(self):
return 'connected-accounts-{0}-application-state'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/base.py
|
OAuth2Provider.request
|
python
|
def request(self, method, url, **kwargs):
user_token = kwargs.pop('token', self.token)
token, secret, expires_at = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] = token
kwargs['params'] = params
return super(OAuth2Provider, self).request(method, url, **kwargs)
|
Build remote url request. Constructs necessary auth.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L331-L339
|
[
"def request(self, method, url, **kwargs):\n \"\"\"Build remote url request.\"\"\"\n return request(method, url, **kwargs)\n",
"def parse_raw_token(self, raw_token):\n \"\"\"Parse token and secret from raw token response.\"\"\"\n if raw_token is None:\n return (None, None, None)\n # Load as json first then parse as query string\n try:\n token_data = json.loads(raw_token)\n except ValueError:\n qs = parse_qs(raw_token)\n token = qs.get('access_token', [None])[0]\n refresh_token = qs.get('refresh_token', [None])[0]\n expires_at = qs.get(self.expires_in_key, [None])[0]\n else:\n token = token_data.get('access_token', None)\n refresh_token = token_data.get('refresh_token', None)\n expires_at = token_data.get(self.expires_in_key, None)\n\n if expires_at:\n expires_at = timezone.now() + timedelta(seconds=int(expires_at))\n\n return (token, refresh_token, expires_at)\n"
] |
class OAuth2Provider(BaseOAuthProvider):
supports_state = True
expires_in_key = 'expires_in'
auth_params = {}
def check_application_state(self, request):
"""Check optional state parameter."""
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check = constant_time_compare(stored, returned)
else:
logger.error('No state parameter returned by the provider.')
else:
logger.error('No state stored in the sesssion.')
return check
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
callback = request.build_absolute_uri(callback or request.path)
if not self.check_application_state(request):
logger.error('Application state check failed.')
return None
if 'code' in request.GET:
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'client_secret': self.consumer_secret,
'code': request.GET['code'],
'grant_type': 'authorization_code',
}
else:
logger.error('No code returned by the provider')
return None
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def refresh_access_token(self, raw_token, **kwargs):
token, refresh_token, expires_at = self.parse_raw_token(raw_token)
refresh_token = kwargs.pop('refresh_token', refresh_token)
args = {
'client_id': self.consumer_key,
'client_secret': self.consumer_secret,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
}
try:
response = self.request('post', self.access_token_url, data=args)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch access token: {0}'.format(e))
return None
else:
return response.text
def get_application_state(self, request, callback):
"""Generate state optional parameter."""
return get_random_string(32)
def get_auth_params(self, request, action=None):
return self.auth_params
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope = self.get_scope(request)
if scope:
args['scope'] = self.scope_separator.join(self.get_scope(request))
state = self.get_application_state(request, callback)
if state is not None:
args['state'] = state
request.session[self.session_key] = state
auth_params = self.get_auth_params(request)
if auth_params:
args.update(auth_params)
return args
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = parse_qs(raw_token)
token = qs.get('access_token', [None])[0]
refresh_token = qs.get('refresh_token', [None])[0]
expires_at = qs.get(self.expires_in_key, [None])[0]
else:
token = token_data.get('access_token', None)
refresh_token = token_data.get('refresh_token', None)
expires_at = token_data.get(self.expires_in_key, None)
if expires_at:
expires_at = timezone.now() + timedelta(seconds=int(expires_at))
return (token, refresh_token, expires_at)
@property
def session_key(self):
return 'connected-accounts-{0}-application-state'.format(self.id)
|
mishbahr/django-connected
|
connected_accounts/providers/mailchimp.py
|
MailChimpProvider.get_profile_data
|
python
|
def get_profile_data(self, raw_token):
token_data = json.loads(raw_token)
# This header is the 'magic' that makes this empty GET request work.
headers = {'Authorization': 'OAuth %s' % token_data['access_token']}
try:
response = self.request('get', self.profile_url, headers=headers)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch user profile: {0}'.format(e))
return None
else:
return response.json() or response.text
|
Fetch user profile information.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/mailchimp.py#L49-L62
|
[
"def request(self, method, url, **kwargs):\n \"\"\"Build remote url request. Constructs necessary auth.\"\"\"\n user_token = kwargs.pop('token', self.token)\n token, secret, expires_at = self.parse_raw_token(user_token)\n if token is not None:\n params = kwargs.get('params', {})\n params['access_token'] = token\n kwargs['params'] = params\n return super(OAuth2Provider, self).request(method, url, **kwargs)\n"
] |
class MailChimpProvider(OAuth2Provider):
id = 'mailchimp'
name = _('MailChimp')
account_class = MailChimpAccount
expires_in_key = ''
authorization_url = 'https://login.mailchimp.com/oauth2/authorize'
access_token_url = 'https://login.mailchimp.com/oauth2/token'
profile_url = 'https://login.mailchimp.com/oauth2/metadata'
consumer_key = settings.CONNECTED_ACCOUNTS_MAILCHIMP_CONSUMER_KEY
consumer_secret = settings.CONNECTED_ACCOUNTS_MAILCHIMP_CONSUMER_SECRET
def extract_uid(self, data):
"""Return unique identifier from the profile info."""
return data.get('user_id', None)
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthProvidertMixin.get_provider
|
python
|
def get_provider(self, provider):
if self.provider is not None:
return self.provider
return providers.by_id(provider)
|
Get instance of the OAuth client for this provider.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L25-L29
|
[
"def by_id(self, id):\n self.discover_providers()\n return self.provider_map.get(id)\n"
] |
class OAuthProvidertMixin(object):
"""Mixin for getting OAuth client for a provider."""
provider = None
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthRedirect.get_callback_url
|
python
|
def get_callback_url(self, provider):
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id})
|
Return the callback url for this provider.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L42-L45
| null |
class OAuthRedirect(OAuthProvidertMixin, RedirectView):
"""Redirect user to OAuth provider to enable access."""
model = Account
permanent = False
def get_additional_parameters(self, provider):
"""Return additional redirect parameters for this provider."""
return {}
def get_redirect_url(self, **kwargs):
"""Build redirect url for a given provider."""
provider_id = kwargs.get('provider', '')
provider = self.get_provider(provider_id)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
params = self.get_additional_parameters(provider)
return provider.get_redirect_url(self.request, callback=callback, parameters=params)
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthRedirect.get_redirect_url
|
python
|
def get_redirect_url(self, **kwargs):
provider_id = kwargs.get('provider', '')
provider = self.get_provider(provider_id)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
params = self.get_additional_parameters(provider)
return provider.get_redirect_url(self.request, callback=callback, parameters=params)
|
Build redirect url for a given provider.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L47-L55
| null |
class OAuthRedirect(OAuthProvidertMixin, RedirectView):
"""Redirect user to OAuth provider to enable access."""
model = Account
permanent = False
def get_additional_parameters(self, provider):
"""Return additional redirect parameters for this provider."""
return {}
def get_callback_url(self, provider):
"""Return the callback url for this provider."""
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id})
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthCallback.get_login_redirect
|
python
|
def get_login_redirect(self, provider, account):
info = self.model._meta.app_label, self.model._meta.model_name
# inline import to prevent circular imports.
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse('admin:%s_%s_changelist' % info)
if preserved_filters:
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': self.model._meta}, redirect_url)
return redirect_url
|
Return url to redirect authenticated users.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L119-L129
| null |
class OAuthCallback(OAuthProvidertMixin, View):
"""Base OAuth callback view."""
model = Account
def get(self, request, *args, **kwargs):
name = kwargs.get('provider', '')
provider = self.get_provider(name)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
# Fetch access token
raw_token = provider.get_access_token(self.request, callback=callback)
if raw_token is None:
return self.handle_login_failure(provider, 'Could not retrieve token.')
# Fetch profile info
profile_data = provider.get_profile_data(raw_token)
if profile_data is None:
return self.handle_login_failure(provider, 'Could not retrieve profile.')
identifier = provider.extract_uid(profile_data)
if identifier is None:
return self.handle_login_failure(provider, 'Could not determine uid.')
token, token_secret, expires_at = provider.parse_raw_token(raw_token)
account_defaults = {
'raw_token': raw_token,
'oauth_token': token,
'oauth_token_secret': token_secret,
'user': self.request.user,
'extra_data': provider.extract_extra_data(profile_data),
'expires_at': expires_at,
}
account, created = Account.objects.get_or_create(
provider=provider.id, uid=identifier, defaults=account_defaults
)
opts = account._meta
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(account)}
if created:
msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
else:
for (key, value) in account_defaults.iteritems():
setattr(account, key, value)
account.save()
msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
return redirect(self.get_login_redirect(provider, account))
def get_callback_url(self, provider):
"""Return callback url if different than the current url."""
return None
def get_error_redirect(self, provider, reason):
"""Return url to redirect on login failure."""
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_changelist' % info)
def handle_login_failure(self, provider, reason):
"""Message user and redirect on error."""
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason))
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthCallback.get_error_redirect
|
python
|
def get_error_redirect(self, provider, reason):
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_changelist' % info)
|
Return url to redirect on login failure.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L131-L134
| null |
class OAuthCallback(OAuthProvidertMixin, View):
"""Base OAuth callback view."""
model = Account
def get(self, request, *args, **kwargs):
name = kwargs.get('provider', '')
provider = self.get_provider(name)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
# Fetch access token
raw_token = provider.get_access_token(self.request, callback=callback)
if raw_token is None:
return self.handle_login_failure(provider, 'Could not retrieve token.')
# Fetch profile info
profile_data = provider.get_profile_data(raw_token)
if profile_data is None:
return self.handle_login_failure(provider, 'Could not retrieve profile.')
identifier = provider.extract_uid(profile_data)
if identifier is None:
return self.handle_login_failure(provider, 'Could not determine uid.')
token, token_secret, expires_at = provider.parse_raw_token(raw_token)
account_defaults = {
'raw_token': raw_token,
'oauth_token': token,
'oauth_token_secret': token_secret,
'user': self.request.user,
'extra_data': provider.extract_extra_data(profile_data),
'expires_at': expires_at,
}
account, created = Account.objects.get_or_create(
provider=provider.id, uid=identifier, defaults=account_defaults
)
opts = account._meta
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(account)}
if created:
msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
else:
for (key, value) in account_defaults.iteritems():
setattr(account, key, value)
account.save()
msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
return redirect(self.get_login_redirect(provider, account))
def get_callback_url(self, provider):
"""Return callback url if different than the current url."""
return None
def get_login_redirect(self, provider, account):
"""Return url to redirect authenticated users."""
info = self.model._meta.app_label, self.model._meta.model_name
# inline import to prevent circular imports.
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse('admin:%s_%s_changelist' % info)
if preserved_filters:
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': self.model._meta}, redirect_url)
return redirect_url
def handle_login_failure(self, provider, reason):
"""Message user and redirect on error."""
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason))
|
mishbahr/django-connected
|
connected_accounts/views.py
|
OAuthCallback.handle_login_failure
|
python
|
def handle_login_failure(self, provider, reason):
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason))
|
Message user and redirect on error.
|
train
|
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L136-L140
| null |
class OAuthCallback(OAuthProvidertMixin, View):
"""Base OAuth callback view."""
model = Account
def get(self, request, *args, **kwargs):
name = kwargs.get('provider', '')
provider = self.get_provider(name)
if not provider:
raise Http404('Unknown OAuth provider.')
callback = self.get_callback_url(provider)
# Fetch access token
raw_token = provider.get_access_token(self.request, callback=callback)
if raw_token is None:
return self.handle_login_failure(provider, 'Could not retrieve token.')
# Fetch profile info
profile_data = provider.get_profile_data(raw_token)
if profile_data is None:
return self.handle_login_failure(provider, 'Could not retrieve profile.')
identifier = provider.extract_uid(profile_data)
if identifier is None:
return self.handle_login_failure(provider, 'Could not determine uid.')
token, token_secret, expires_at = provider.parse_raw_token(raw_token)
account_defaults = {
'raw_token': raw_token,
'oauth_token': token,
'oauth_token_secret': token_secret,
'user': self.request.user,
'extra_data': provider.extract_extra_data(profile_data),
'expires_at': expires_at,
}
account, created = Account.objects.get_or_create(
provider=provider.id, uid=identifier, defaults=account_defaults
)
opts = account._meta
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(account)}
if created:
msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
else:
for (key, value) in account_defaults.iteritems():
setattr(account, key, value)
account.save()
msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
messages.add_message(request, messages.SUCCESS, msg)
return redirect(self.get_login_redirect(provider, account))
def get_callback_url(self, provider):
"""Return callback url if different than the current url."""
return None
def get_login_redirect(self, provider, account):
"""Return url to redirect authenticated users."""
info = self.model._meta.app_label, self.model._meta.model_name
# inline import to prevent circular imports.
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse('admin:%s_%s_changelist' % info)
if preserved_filters:
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': self.model._meta}, redirect_url)
return redirect_url
def get_error_redirect(self, provider, reason):
"""Return url to redirect on login failure."""
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_changelist' % info)
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._python_rpath
|
python
|
def _python_rpath(self):
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
|
The relative path (from environment root) to python.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L51-L57
| null |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.pip_version
|
python
|
def pip_version(self):
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
|
Version of installed pip.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L60-L68
|
[
"def _execute(self, args, log=True):\n \"\"\"Executes the given command inside the environment and returns the output.\"\"\"\n if not self._ready:\n self.open_or_create()\n output = ''\n error = ''\n try:\n proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, error = proc.communicate()\n returncode = proc.returncode\n if returncode:\n raise subprocess.CalledProcessError(returncode, proc, (output, error))\n return to_text(output)\n except OSError as e:\n # raise a more meaningful error with the program name\n prog = args[0]\n if prog[0] != os.sep:\n prog = os.path.join(self.path, prog)\n raise OSError('%s: %s' % (prog, six.u(str(e))))\n except subprocess.CalledProcessError as e:\n output, error = e.output\n e.output = output\n raise e\n finally:\n if log:\n try:\n self._write_to_log(to_text(output))\n self._write_to_error(to_text(error))\n except NameError:\n pass # We tried\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._create
|
python
|
def _create(self):
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
|
Executes `virtualenv` to create a new environment.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L90-L107
|
[
"def _write_to_log(self, s, truncate=False):\n \"\"\"Writes the given output to the log file, appending unless `truncate` is True.\"\"\"\n # if truncate is True, set write mode to truncate\n with open(self._logfile, 'w' if truncate else 'a') as fp:\n fp.writelines((to_text(s) if six.PY2 else to_text(s), ))\n",
"def _write_to_error(self, s, truncate=False):\n \"\"\"Writes the given output to the error file, appending unless `truncate` is True.\"\"\"\n # if truncate is True, set write mode to truncate\n with open(self._errorfile, 'w' if truncate else 'a') as fp:\n fp.writelines((to_text(s)), )\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._execute_pip
|
python
|
def _execute_pip(self, args, log=True):
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
|
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L109-L127
|
[
"def _execute(self, args, log=True):\n \"\"\"Executes the given command inside the environment and returns the output.\"\"\"\n if not self._ready:\n self.open_or_create()\n output = ''\n error = ''\n try:\n proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, error = proc.communicate()\n returncode = proc.returncode\n if returncode:\n raise subprocess.CalledProcessError(returncode, proc, (output, error))\n return to_text(output)\n except OSError as e:\n # raise a more meaningful error with the program name\n prog = args[0]\n if prog[0] != os.sep:\n prog = os.path.join(self.path, prog)\n raise OSError('%s: %s' % (prog, six.u(str(e))))\n except subprocess.CalledProcessError as e:\n output, error = e.output\n e.output = output\n raise e\n finally:\n if log:\n try:\n self._write_to_log(to_text(output))\n self._write_to_error(to_text(error))\n except NameError:\n pass # We tried\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._execute
|
python
|
def _execute(self, args, log=True):
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass
|
Executes the given command inside the environment and returns the output.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L129-L158
|
[
"def to_text(source):\n if six.PY3:\n if isinstance(source, str):\n return source\n else:\n return source.decode(\"utf-8\")\n elif six.PY2:\n if isinstance(source, unicode):\n return source.encode(\"utf-8\")\n return source\n else:\n return source\n",
"def open_or_create(self):\n \"\"\"Attempts to open the virtual environment or creates it if it\n doesn't exist.\n XXX this should probably be expanded to do some proper checking?\"\"\"\n if not self._pip_exists():\n self._create()\n self._ready = True\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
# We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._write_to_log
|
python
|
def _write_to_log(self, s, truncate=False):
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
|
Writes the given output to the log file, appending unless `truncate` is True.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L160-L164
| null |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._write_to_error
|
python
|
def _write_to_error(self, s, truncate=False):
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
|
Writes the given output to the error file, appending unless `truncate` is True.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L166-L170
| null |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment._pip_exists
|
python
|
def _pip_exists(self):
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
|
Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L172-L175
| null |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.install
|
python
|
def install(self, package, force=False, upgrade=False, options=None):
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
|
Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L185-L225
|
[
"def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n exec_args = list(self._pip)\n\n # Older versions of pip don't support the version check argument.\n # Fixes https://github.com/sjkingo/virtualenv-api/issues/35\n if self.pip_version[0] >= 6:\n exec_args.append('--disable-pip-version-check')\n\n exec_args.extend(args)\n return self._execute(exec_args, log=log)\n",
"def is_installed(self, package):\n \"\"\"Returns True if the given package (given in pip's package syntax or a\n tuple of ('name', 'ver')) is installed in the virtual environment.\"\"\"\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.endswith('.git'):\n pkg_name = os.path.split(package)[1][:-4]\n return pkg_name in self.installed_package_names or \\\n pkg_name.replace('_', '-') in self.installed_package_names\n pkg_tuple = split_package_name(package)\n if pkg_tuple[1] is not None:\n return pkg_tuple in self.installed_packages\n else:\n return pkg_tuple[0].lower() in self.installed_package_names\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.uninstall
|
python
|
def uninstall(self, package):
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
|
Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L227-L238
|
[
"def is_installed(self, package):\n \"\"\"Returns True if the given package (given in pip's package syntax or a\n tuple of ('name', 'ver')) is installed in the virtual environment.\"\"\"\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.endswith('.git'):\n pkg_name = os.path.split(package)[1][:-4]\n return pkg_name in self.installed_package_names or \\\n pkg_name.replace('_', '-') in self.installed_package_names\n pkg_tuple = split_package_name(package)\n if pkg_tuple[1] is not None:\n return pkg_tuple in self.installed_packages\n else:\n return pkg_tuple[0].lower() in self.installed_package_names\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.wheel
|
python
|
def wheel(self, package, options=None):
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
|
Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L240-L264
|
[
"def is_installed(self, package):\n \"\"\"Returns True if the given package (given in pip's package syntax or a\n tuple of ('name', 'ver')) is installed in the virtual environment.\"\"\"\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.endswith('.git'):\n pkg_name = os.path.split(package)[1][:-4]\n return pkg_name in self.installed_package_names or \\\n pkg_name.replace('_', '-') in self.installed_package_names\n pkg_tuple = split_package_name(package)\n if pkg_tuple[1] is not None:\n return pkg_tuple in self.installed_packages\n else:\n return pkg_tuple[0].lower() in self.installed_package_names\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.is_installed
|
python
|
def is_installed(self, package):
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
|
Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L266-L279
|
[
"def split_package_name(p):\n \"\"\"Splits the given package name and returns a tuple (name, ver).\"\"\"\n s = p.split(six.u('=='))\n if len(s) == 1:\n return (to_text(s[0]), None)\n else:\n return (to_text(s[0]), to_text(s[1]))\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.upgrade
|
python
|
def upgrade(self, package, force=False):
self.install(package, upgrade=True, force=force)
|
Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L281-L285
|
[
"def install(self, package, force=False, upgrade=False, options=None):\n \"\"\"Installs the given package into this virtual environment, as\n specified in pip's package syntax or a tuple of ('name', 'ver'),\n only if it is not already installed. Some valid examples:\n\n 'Django'\n 'Django==1.5'\n ('Django', '1.5')\n '-e .'\n '-r requirements.txt'\n\n If `force` is True, force an installation. If `upgrade` is True,\n attempt to upgrade the package in question. If both `force` and\n `upgrade` are True, reinstall the package and its dependencies.\n The `options` is a list of strings that can be used to pass to\n pip.\"\"\"\n if self.readonly:\n raise VirtualenvReadonlyException()\n if options is None:\n options = []\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.startswith(('-e', '-r')):\n package_args = package.split()\n else:\n package_args = [package]\n if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):\n self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])\n return\n if not isinstance(options, list):\n raise ValueError(\"Options must be a list of strings.\")\n if upgrade:\n options += ['--upgrade']\n if force:\n options += ['--force-reinstall']\n elif force:\n options += ['--ignore-installed']\n try:\n self._execute_pip(['install'] + package_args + options)\n except subprocess.CalledProcessError as e:\n raise PackageInstallationException((e.returncode, e.output, package))\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.upgrade_all
|
python
|
def upgrade_all(self):
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
|
Upgrades all installed packages to their latest versions.
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L287-L292
|
[
"def install(self, package, force=False, upgrade=False, options=None):\n \"\"\"Installs the given package into this virtual environment, as\n specified in pip's package syntax or a tuple of ('name', 'ver'),\n only if it is not already installed. Some valid examples:\n\n 'Django'\n 'Django==1.5'\n ('Django', '1.5')\n '-e .'\n '-r requirements.txt'\n\n If `force` is True, force an installation. If `upgrade` is True,\n attempt to upgrade the package in question. If both `force` and\n `upgrade` are True, reinstall the package and its dependencies.\n The `options` is a list of strings that can be used to pass to\n pip.\"\"\"\n if self.readonly:\n raise VirtualenvReadonlyException()\n if options is None:\n options = []\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.startswith(('-e', '-r')):\n package_args = package.split()\n else:\n package_args = [package]\n if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):\n self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])\n return\n if not isinstance(options, list):\n raise ValueError(\"Options must be a list of strings.\")\n if upgrade:\n options += ['--upgrade']\n if force:\n options += ['--force-reinstall']\n elif force:\n options += ['--ignore-installed']\n try:\n self._execute_pip(['install'] + package_args + options)\n except subprocess.CalledProcessError as e:\n raise PackageInstallationException((e.returncode, e.output, package))\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.search
|
python
|
def search(self, term):
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
|
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L294-L315
|
[
"def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n exec_args = list(self._pip)\n\n # Older versions of pip don't support the version check argument.\n # Fixes https://github.com/sjkingo/virtualenv-api/issues/35\n if self.pip_version[0] >= 6:\n exec_args.append('--disable-pip-version-check')\n\n exec_args.extend(args)\n return self._execute(exec_args, log=log)\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search_names(self, term):
return list(self.search(term).keys())
@property
def installed_packages(self):
"""
List of all packages that are installed in this environment in
the format [(name, ver), ..].
"""
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/manage.py
|
VirtualEnvironment.installed_packages
|
python
|
def installed_packages(self):
freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l']
return list(map(split_package_name, filter(None, self._execute_pip(
['freeze'] + freeze_options).split(linesep))))
|
List of all packages that are installed in this environment in
the format [(name, ver), ..].
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L321-L328
|
[
"def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n exec_args = list(self._pip)\n\n # Older versions of pip don't support the version check argument.\n # Fixes https://github.com/sjkingo/virtualenv-api/issues/35\n if self.pip_version[0] >= 6:\n exec_args.append('--disable-pip-version-check')\n\n exec_args.extend(args)\n return self._execute(exec_args, log=log)\n"
] |
class VirtualEnvironment(object):
def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False):
if path is None:
path = get_env_path()
if not path:
raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not activate')
self.python = python
self.system_site_packages = system_site_packages
# remove trailing slash so os.path.split() behaves correctly
if path[-1] == os.path.sep:
path = path[:-1]
# Expand path so shell shortcuts may be used such as ~
self.path = os.path.abspath(os.path.expanduser(path))
self.env = environ.copy()
if cache is not None:
self.env['PIP_DOWNLOAD_CACHE'] = os.path.expanduser(os.path.expandvars(cache))
self.readonly = readonly
# True if the virtual environment has been set up through open_or_create()
self._ready = False
def __str__(self):
return six.u(self.path)
@property
def _pip(self):
"""The arguments used to call pip."""
# pip is called using the python interpreter to get around a long path
# issue detailed in https://github.com/sjkingo/virtualenv-api/issues/30
return [self._python_rpath, '-m', 'pip']
@property
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
return os.path.join('bin', 'python')
@property
def pip_version(self):
"""Version of installed pip."""
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in output.split('.')])
return self._pip_version
@property
def root(self):
"""The root directory that this virtual environment exists in."""
return os.path.split(self.path)[0]
@property
def name(self):
"""The name of this virtual environment (taken from its path)."""
return os.path.basename(self.path)
@property
def _logfile(self):
"""Absolute path of the log file for recording installation output."""
return os.path.join(self.path, 'build.log')
@property
def _errorfile(self):
"""Absolute path of the log file for recording installation errors."""
return os.path.join(self.path, 'build.err')
def _create(self):
"""Executes `virtualenv` to create a new environment."""
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, self.name])
proc = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise VirtualenvCreationException((returncode, output, self.name))
self._write_to_log(output, truncate=True)
self._write_to_error(error, truncate=True)
def _execute_pip(self, args, log=True):
"""
Executes pip commands.
:param args: Arguments to pass to pip (list[str])
:param log: Log the output to a file [default: True] (boolean)
:return: See _execute
"""
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disable-pip-version-check')
exec_args.extend(args)
return self._execute(exec_args, log=log)
def _execute(self, args, log=True):
"""Executes the given command inside the environment and returns the output."""
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncode
if returncode:
raise subprocess.CalledProcessError(returncode, proc, (output, error))
return to_text(output)
except OSError as e:
# raise a more meaningful error with the program name
prog = args[0]
if prog[0] != os.sep:
prog = os.path.join(self.path, prog)
raise OSError('%s: %s' % (prog, six.u(str(e))))
except subprocess.CalledProcessError as e:
output, error = e.output
e.output = output
raise e
finally:
if log:
try:
self._write_to_log(to_text(output))
self._write_to_error(to_text(error))
except NameError:
pass # We tried
def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), )
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def open_or_create(self):
"""Attempts to open the virtual environment or creates it if it
doesn't exist.
XXX this should probably be expanded to do some proper checking?"""
if not self._pip_exists():
self._create()
self._ready = True
def install(self, package, force=False, upgrade=False, options=None):
"""Installs the given package into this virtual environment, as
specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
'-e .'
'-r requirements.txt'
If `force` is True, force an installation. If `upgrade` is True,
attempt to upgrade the package in question. If both `force` and
`upgrade` are True, reinstall the package and its dependencies.
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if package.startswith(('-e', '-r')):
package_args = package.split()
else:
package_args = [package]
if not (force or upgrade) and (package_args[0] != '-r' and self.is_installed(package_args[-1])):
self._write_to_log('%s is already installed, skipping (use force=True to override)' % package_args[-1])
return
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
if upgrade:
options += ['--upgrade']
if force:
options += ['--force-reinstall']
elif force:
options += ['--ignore-installed']
try:
self._execute_pip(['install'] + package_args + options)
except subprocess.CalledProcessError as e:
raise PackageInstallationException((e.returncode, e.output, package))
def uninstall(self, package):
"""Uninstalls the given package (given in pip's package syntax or a tuple of
('name', 'ver')) from this virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed(package):
self._write_to_log('%s is not installed, skipping' % package)
return
try:
self._execute_pip(['uninstall', '-y', package])
except subprocess.CalledProcessError as e:
raise PackageRemovalException((e.returncode, e.output, package))
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strings that can be used to pass to
pip."""
if self.readonly:
raise VirtualenvReadonlyException()
if options is None:
options = []
if isinstance(package, tuple):
package = '=='.join(package)
if not self.is_installed('wheel'):
raise PackageWheelException((0, "Wheel package must be installed in the virtual environment", package))
if not isinstance(options, list):
raise ValueError("Options must be a list of strings.")
try:
self._execute_pip(['wheel', package] + options)
except subprocess.CalledProcessError as e:
raise PackageWheelException((e.returncode, e.output, package))
def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True,
the package and all of its dependencies will be reinstalled, otherwise
if the package is up to date, this command is a no-op."""
self.install(package, upgrade=True, force=force)
def upgrade_all(self):
"""
Upgrades all installed packages to their latest versions.
"""
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True)
def search(self, term):
"""
Searches the PyPi repository for the given `term` and returns a
dictionary of results.
New in 2.1.5: returns a dictionary instead of list of tuples
"""
packages = {}
results = self._execute_pip(['search', term], log=False) # Don't want to log searches
for result in results.split(linesep):
try:
name, description = result.split(six.u(' - '), 1)
except ValueError:
# '-' not in result so unable to split into tuple;
# this could be from a multi-line description
continue
else:
name = name.strip()
if len(name) == 0:
continue
packages[name] = description.split(six.u('<br'), 1)[0].strip()
return packages
def search_names(self, term):
return list(self.search(term).keys())
@property
@property
def installed_package_names(self):
"""List of all package names that are installed in this environment."""
return [name.lower() for name, _ in self.installed_packages]
|
sjkingo/virtualenv-api
|
virtualenvapi/util.py
|
split_package_name
|
python
|
def split_package_name(p):
s = p.split(six.u('=='))
if len(s) == 1:
return (to_text(s[0]), None)
else:
return (to_text(s[0]), to_text(s[1]))
|
Splits the given package name and returns a tuple (name, ver).
|
train
|
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/util.py#L40-L46
|
[
"def to_text(source):\n if six.PY3:\n if isinstance(source, str):\n return source\n else:\n return source.decode(\"utf-8\")\n elif six.PY2:\n if isinstance(source, unicode):\n return source.encode(\"utf-8\")\n return source\n else:\n return source\n"
] |
from os import environ
import six
import sys
def to_text(source):
if six.PY3:
if isinstance(source, str):
return source
else:
return source.decode("utf-8")
elif six.PY2:
if isinstance(source, unicode):
return source.encode("utf-8")
return source
else:
return source
def to_ascii(source):
if isinstance(source, six.string_types):
return "".join([c for c in source if ord(c) < 128])
def get_env_path():
prefix_name = 'real_prefix'
virtual_env_path_environ_key = 'VIRTUAL_ENV'
path = None
real_prefix = (hasattr(sys, prefix_name) and getattr(sys, prefix_name)) or None
if real_prefix:
path = environ.get(virtual_env_path_environ_key)
if not path:
path = sys.prefix
return path
|
davidrpugh/pyCollocation
|
pycollocation/basis_functions/basis_splines.py
|
BSplineBasis._basis_spline_factory
|
python
|
def _basis_spline_factory(coef, degree, knots, der, ext):
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext)
|
Return a B-Spline given some coefficients.
|
train
|
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L18-L20
| null |
class BSplineBasis(basis_functions.BasisFunctionLike):
@staticmethod
@classmethod
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a the derivative of a B-spline.
"""
return cls._basis_spline_factory(coef, degree, knots, 1, ext)
@classmethod
def fit(cls, *args, **kwargs):
"""Possibly just wrap interpolate.splprep?"""
return interpolate.splprep(*args, **kwargs)
@classmethod
def functions_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a B-spline.
"""
return cls._basis_spline_factory(coef, degree, knots, 0, ext)
|
davidrpugh/pyCollocation
|
pycollocation/basis_functions/basis_splines.py
|
BSplineBasis.derivatives_factory
|
python
|
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs):
return cls._basis_spline_factory(coef, degree, knots, 1, ext)
|
Given some coefficients, return a the derivative of a B-spline.
|
train
|
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L23-L28
| null |
class BSplineBasis(basis_functions.BasisFunctionLike):
@staticmethod
def _basis_spline_factory(coef, degree, knots, der, ext):
"""Return a B-Spline given some coefficients."""
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext)
@classmethod
@classmethod
def fit(cls, *args, **kwargs):
"""Possibly just wrap interpolate.splprep?"""
return interpolate.splprep(*args, **kwargs)
@classmethod
def functions_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a B-spline.
"""
return cls._basis_spline_factory(coef, degree, knots, 0, ext)
|
davidrpugh/pyCollocation
|
pycollocation/basis_functions/basis_splines.py
|
BSplineBasis.functions_factory
|
python
|
def functions_factory(cls, coef, degree, knots, ext, **kwargs):
return cls._basis_spline_factory(coef, degree, knots, 0, ext)
|
Given some coefficients, return a B-spline.
|
train
|
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L36-L41
| null |
class BSplineBasis(basis_functions.BasisFunctionLike):
@staticmethod
def _basis_spline_factory(coef, degree, knots, der, ext):
"""Return a B-Spline given some coefficients."""
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext)
@classmethod
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a the derivative of a B-spline.
"""
return cls._basis_spline_factory(coef, degree, knots, 1, ext)
@classmethod
def fit(cls, *args, **kwargs):
"""Possibly just wrap interpolate.splprep?"""
return interpolate.splprep(*args, **kwargs)
@classmethod
|
davidrpugh/pyCollocation
|
pycollocation/solvers/solvers.py
|
SolverLike._evaluate_rhs
|
python
|
def _evaluate_rhs(cls, funcs, nodes, problem):
evald_funcs = cls._evaluate_functions(funcs, nodes)
evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params)
return evald_rhs
|
Compute the value of the right-hand side of the system of ODEs.
Parameters
----------
basis_funcs : list(function)
nodes : numpy.ndarray
problem : TwoPointBVPLike
Returns
-------
evaluated_rhs : list(float)
|
train
|
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L41-L58
| null |
class SolverLike(object):
"""
Class describing the protocol the all SolverLike objects should satisfy.
Notes
-----
Subclasses should implement `solve` method as described below.
"""
@property
def basis_functions(self):
r"""
Functions used to approximate the solution to a boundary value problem.
:getter: Return the current basis functions.
:type: `basis_functions.BasisFunctions`
"""
return self._basis_functions
@staticmethod
def _array_to_list(coefs_array, indices_or_sections, axis=0):
"""Split an array into a list of arrays."""
return np.split(coefs_array, indices_or_sections, axis)
@staticmethod
def _evaluate_functions(funcs, points):
"""Evaluate a list of functions at some points."""
return [func(points) for func in funcs]
@classmethod
@classmethod
def _lower_boundary_residual(cls, funcs, problem, ts):
evald_funcs = cls._evaluate_functions(funcs, ts)
return problem.bcs_lower(ts, *evald_funcs, **problem.params)
@classmethod
def _upper_boundary_residual(cls, funcs, problem, ts):
evald_funcs = cls._evaluate_functions(funcs, ts)
return problem.bcs_upper(ts, *evald_funcs, **problem.params)
@classmethod
def _compute_boundary_residuals(cls, boundary_points, funcs, problem):
boundary_residuals = []
if problem.bcs_lower is not None:
residual = cls._lower_boundary_residual_factory(funcs, problem)
boundary_residuals.append(residual(boundary_points[0]))
if problem.bcs_upper is not None:
residual = cls._upper_boundary_residual_factory(funcs, problem)
boundary_residuals.append(residual(boundary_points[1]))
return boundary_residuals
@classmethod
def _compute_interior_residuals(cls, derivs, funcs, nodes, problem):
interior_residuals = cls._interior_residuals_factory(derivs, funcs, problem)
residuals = interior_residuals(nodes)
return residuals
@classmethod
def _interior_residuals(cls, derivs, funcs, problem, ts):
evaluated_lhs = cls._evaluate_functions(derivs, ts)
evaluated_rhs = cls._evaluate_rhs(funcs, ts, problem)
return [lhs - rhs for lhs, rhs in zip(evaluated_lhs, evaluated_rhs)]
@classmethod
def _interior_residuals_factory(cls, derivs, funcs, problem):
return functools.partial(cls._interior_residuals, derivs, funcs, problem)
@classmethod
def _lower_boundary_residual_factory(cls, funcs, problem):
return functools.partial(cls._lower_boundary_residual, funcs, problem)
@classmethod
def _upper_boundary_residual_factory(cls, funcs, problem):
return functools.partial(cls._upper_boundary_residual, funcs, problem)
def _assess_approximation(self, boundary_points, derivs, funcs, nodes, problem):
"""
Parameters
----------
basis_derivs : list(function)
basis_funcs : list(function)
problem : TwoPointBVPLike
Returns
-------
resids : numpy.ndarray
"""
interior_residuals = self._compute_interior_residuals(derivs, funcs,
nodes, problem)
boundary_residuals = self._compute_boundary_residuals(boundary_points,
funcs, problem)
return np.hstack(interior_residuals + boundary_residuals)
def _compute_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem):
"""
Return collocation residuals.
Parameters
----------
coefs_array : numpy.ndarray
basis_kwargs : dict
problem : TwoPointBVPLike
Returns
-------
resids : numpy.ndarray
"""
coefs_list = self._array_to_list(coefs_array, problem.number_odes)
derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list)
resids = self._assess_approximation(boundary_points, derivs, funcs,
nodes, problem)
return resids
def _construct_approximation(self, basis_kwargs, coefs_list):
"""
Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str: )
coefs_list : list(numpy.ndarray)
Returns
-------
basis_derivs : list(function)
basis_funcs : list(function)
"""
derivs = self._construct_derivatives(coefs_list, **basis_kwargs)
funcs = self._construct_functions(coefs_list, **basis_kwargs)
return derivs, funcs
def _construct_derivatives(self, coefs, **kwargs):
"""Return a list of derivatives given a list of coefficients."""
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs]
def _construct_functions(self, coefs, **kwargs):
"""Return a list of functions given a list of coefficients."""
return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs]
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):
"""
Construct a representation of the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str : )
coefs_array : numpy.ndarray
problem : TwoPointBVPLike
result : OptimizeResult
Returns
-------
solution : SolutionLike
"""
soln_coefs = self._array_to_list(coefs_array, problem.number_odes)
soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs)
soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs)
soln_residual_func = self._interior_residuals_factory(soln_derivs,
soln_funcs,
problem)
solution = solutions.Solution(basis_kwargs, soln_funcs, nodes, problem,
soln_residual_func, result)
return solution
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem,
**solver_options):
"""
Solve a boundary value problem using the collocation method.
Parameters
----------
basis_kwargs : dict
Dictionary of keyword arguments used to build basis functions.
coefs_array : numpy.ndarray
Array of coefficients for basis functions defining the initial
condition.
problem : bvp.TwoPointBVPLike
A two-point boundary value problem (BVP) to solve.
solver_options : dict
Dictionary of options to pass to the non-linear equation solver.
Return
------
solution: solutions.SolutionLike
An instance of the SolutionLike class representing the solution to
the two-point boundary value problem (BVP)
Notes
-----
"""
raise NotImplementedError
|
davidrpugh/pyCollocation
|
pycollocation/solvers/solvers.py
|
SolverLike._assess_approximation
|
python
|
def _assess_approximation(self, boundary_points, derivs, funcs, nodes, problem):
interior_residuals = self._compute_interior_residuals(derivs, funcs,
nodes, problem)
boundary_residuals = self._compute_boundary_residuals(boundary_points,
funcs, problem)
return np.hstack(interior_residuals + boundary_residuals)
|
Parameters
----------
basis_derivs : list(function)
basis_funcs : list(function)
problem : TwoPointBVPLike
Returns
-------
resids : numpy.ndarray
|
train
|
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L105-L122
| null |
class SolverLike(object):
"""
Class describing the protocol the all SolverLike objects should satisfy.
Notes
-----
Subclasses should implement `solve` method as described below.
"""
@property
def basis_functions(self):
r"""
Functions used to approximate the solution to a boundary value problem.
:getter: Return the current basis functions.
:type: `basis_functions.BasisFunctions`
"""
return self._basis_functions
@staticmethod
def _array_to_list(coefs_array, indices_or_sections, axis=0):
"""Split an array into a list of arrays."""
return np.split(coefs_array, indices_or_sections, axis)
@staticmethod
def _evaluate_functions(funcs, points):
"""Evaluate a list of functions at some points."""
return [func(points) for func in funcs]
@classmethod
def _evaluate_rhs(cls, funcs, nodes, problem):
"""
Compute the value of the right-hand side of the system of ODEs.
Parameters
----------
basis_funcs : list(function)
nodes : numpy.ndarray
problem : TwoPointBVPLike
Returns
-------
evaluated_rhs : list(float)
"""
evald_funcs = cls._evaluate_functions(funcs, nodes)
evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params)
return evald_rhs
@classmethod
def _lower_boundary_residual(cls, funcs, problem, ts):
evald_funcs = cls._evaluate_functions(funcs, ts)
return problem.bcs_lower(ts, *evald_funcs, **problem.params)
@classmethod
def _upper_boundary_residual(cls, funcs, problem, ts):
evald_funcs = cls._evaluate_functions(funcs, ts)
return problem.bcs_upper(ts, *evald_funcs, **problem.params)
@classmethod
def _compute_boundary_residuals(cls, boundary_points, funcs, problem):
boundary_residuals = []
if problem.bcs_lower is not None:
residual = cls._lower_boundary_residual_factory(funcs, problem)
boundary_residuals.append(residual(boundary_points[0]))
if problem.bcs_upper is not None:
residual = cls._upper_boundary_residual_factory(funcs, problem)
boundary_residuals.append(residual(boundary_points[1]))
return boundary_residuals
@classmethod
def _compute_interior_residuals(cls, derivs, funcs, nodes, problem):
interior_residuals = cls._interior_residuals_factory(derivs, funcs, problem)
residuals = interior_residuals(nodes)
return residuals
@classmethod
def _interior_residuals(cls, derivs, funcs, problem, ts):
evaluated_lhs = cls._evaluate_functions(derivs, ts)
evaluated_rhs = cls._evaluate_rhs(funcs, ts, problem)
return [lhs - rhs for lhs, rhs in zip(evaluated_lhs, evaluated_rhs)]
@classmethod
def _interior_residuals_factory(cls, derivs, funcs, problem):
return functools.partial(cls._interior_residuals, derivs, funcs, problem)
@classmethod
def _lower_boundary_residual_factory(cls, funcs, problem):
return functools.partial(cls._lower_boundary_residual, funcs, problem)
@classmethod
def _upper_boundary_residual_factory(cls, funcs, problem):
return functools.partial(cls._upper_boundary_residual, funcs, problem)
def _compute_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem):
"""
Return collocation residuals.
Parameters
----------
coefs_array : numpy.ndarray
basis_kwargs : dict
problem : TwoPointBVPLike
Returns
-------
resids : numpy.ndarray
"""
coefs_list = self._array_to_list(coefs_array, problem.number_odes)
derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list)
resids = self._assess_approximation(boundary_points, derivs, funcs,
nodes, problem)
return resids
def _construct_approximation(self, basis_kwargs, coefs_list):
"""
Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str: )
coefs_list : list(numpy.ndarray)
Returns
-------
basis_derivs : list(function)
basis_funcs : list(function)
"""
derivs = self._construct_derivatives(coefs_list, **basis_kwargs)
funcs = self._construct_functions(coefs_list, **basis_kwargs)
return derivs, funcs
def _construct_derivatives(self, coefs, **kwargs):
"""Return a list of derivatives given a list of coefficients."""
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs]
def _construct_functions(self, coefs, **kwargs):
"""Return a list of functions given a list of coefficients."""
return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs]
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):
"""
Construct a representation of the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str : )
coefs_array : numpy.ndarray
problem : TwoPointBVPLike
result : OptimizeResult
Returns
-------
solution : SolutionLike
"""
soln_coefs = self._array_to_list(coefs_array, problem.number_odes)
soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs)
soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs)
soln_residual_func = self._interior_residuals_factory(soln_derivs,
soln_funcs,
problem)
solution = solutions.Solution(basis_kwargs, soln_funcs, nodes, problem,
soln_residual_func, result)
return solution
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem,
**solver_options):
"""
Solve a boundary value problem using the collocation method.
Parameters
----------
basis_kwargs : dict
Dictionary of keyword arguments used to build basis functions.
coefs_array : numpy.ndarray
Array of coefficients for basis functions defining the initial
condition.
problem : bvp.TwoPointBVPLike
A two-point boundary value problem (BVP) to solve.
solver_options : dict
Dictionary of options to pass to the non-linear equation solver.
Return
------
solution: solutions.SolutionLike
An instance of the SolutionLike class representing the solution to
the two-point boundary value problem (BVP)
Notes
-----
"""
raise NotImplementedError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.