signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def unwrap( <EOL>self, algorithm, wrapped_key, wrapped_key_algorithm, wrapped_key_type, additional_associated_data=None<EOL>):<EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Wrap content key. :param str algorithm: Text description of algorithm to use to unwrap key :param bytes content_key: Raw content key to wrap :param str wrapped_key_algorithm: Text description of algorithm for unwrapped key to use :param EncryptionKeyType wrapped_key_type: Type of key to treat key as once unwrapped :param dict additional_associated_data: Not used by all delegated keys, but if it is, then if it is provided on wrap it must be required on unwrap. :returns: Delegated key using unwrapped key :rtype: DelegatedKey
f5643:c0:m6
def sign(self, algorithm, data): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Sign data. :param str algorithm: Text description of algorithm to use to sign data :param bytes data: Data to sign :returns: Signature value :rtype: bytes
f5643:c0:m7
def verify(self, algorithm, signature, data): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Sign data. :param str algorithm: Text description of algorithm to use to verify signature :param bytes signature: Signature to verify :param bytes data: Data over which to verify signature
f5643:c0:m8
def signing_algorithm(self): <EOL>
_raise_not_implemented("<STR_LIT>")<EOL>
Provide a description that can inform an appropriate cryptographic materials provider about how to build a :class:`DelegatedKey` for signature verification. If implemented, the return value of this method is included in the material description written to the encrypted item. :returns: Signing algorithm identifier :rtype: str
f5643:c0:m9
def read(*args):
return io.open(os.path.join(HERE, *args), encoding="<STR_LIT:utf-8>").read()<EOL>
Reads complete file contents.
f5644:m0
def get_version():
init = read("<STR_LIT:src>", "<STR_LIT>", "<STR_LIT>")<EOL>return VERSION_RE.search(init).group(<NUM_LIT:1>)<EOL>
Reads the version from this module.
f5644:m1
def get_requirements():
requirements = read("<STR_LIT>")<EOL>return [r for r in requirements.strip().splitlines()]<EOL>
Reads the requirements file.
f5644:m2
def get(self):
self.log.debug('<STR_LIT>')<EOL>if self.format == "<STR_LIT>":<EOL><INDENT>if self.urlOrPath[:<NUM_LIT:4>] == "<STR_LIT:http>" or self.urlOrPath[:<NUM_LIT:4>] == "<STR_LIT>":<EOL><INDENT>ebook = self._url_to_epub()<EOL><DEDENT>elif "<STR_LIT>" in self.urlOrPath:<EOL><INDENT>ebook = self._docx_to_epub()<EOL><DEDENT><DEDENT>if self.format == "<STR_LIT>":<EOL><INDENT>if self.urlOrPath[:<NUM_LIT:4>] == "<STR_LIT:http>" or self.urlOrPath[:<NUM_LIT:4>] == "<STR_LIT>":<EOL><INDENT>epub = self._url_to_epub()<EOL><DEDENT>elif "<STR_LIT>" in self.urlOrPath:<EOL><INDENT>epub = self._docx_to_epub()<EOL><DEDENT>if not epub:<EOL><INDENT>return None<EOL><DEDENT>ebook = self._epub_to_mobi(<EOL>epubPath=epub,<EOL>deleteEpub=False<EOL>)<EOL><DEDENT>tag(<EOL>log=self.log,<EOL>filepath=ebook,<EOL>tags=False,<EOL>rating=False,<EOL>wherefrom=self.url<EOL>)<EOL>self.log.debug('<STR_LIT>')<EOL>return ebook<EOL>
*get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage
f5650:c0:m1
def _url_to_epub(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>from polyglot import htmlCleaner<EOL>cleaner = htmlCleaner(<EOL>log=self.log,<EOL>settings=self.settings,<EOL>url=self.urlOrPath,<EOL>outputDirectory=self.outputDirectory,<EOL>title=self.title, <EOL>style=False, <EOL>metadata=True, <EOL>h1=False <EOL>)<EOL>html = cleaner.clean()<EOL>if not html:<EOL><INDENT>return None<EOL><DEDENT>if self.footer:<EOL><INDENT>footer = self._tmp_html_file(self.footer)<EOL>footer = '<STR_LIT>' % locals()<EOL><DEDENT>else:<EOL><INDENT>footer = "<STR_LIT>"<EOL><DEDENT>if self.header:<EOL><INDENT>header = self._tmp_html_file(self.header)<EOL>header = '<STR_LIT>' % locals()<EOL><DEDENT>else:<EOL><INDENT>header = "<STR_LIT>"<EOL><DEDENT>epub = html.replace("<STR_LIT>", "<STR_LIT>")<EOL>pandoc = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals(<EOL>)<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>try:<EOL><INDENT>with open(epub):<EOL><INDENT>pass<EOL><DEDENT>fileExists = True<EOL><DEDENT>except IOError:<EOL><INDENT>fileExists = False<EOL>raise IOError(<EOL>"<STR_LIT>" % (epub, stderr))<EOL><DEDENT>os.remove(html)<EOL>self.log.debug('<STR_LIT>')<EOL>return epub<EOL>
*generate the epub book from a URL*
f5650:c0:m2
def _tmp_html_file(<EOL>self,<EOL>content):
self.log.debug('<STR_LIT>')<EOL>content =
*create a tmp html file with some content used for the header or footer of the ebook* **Key Arguments:** - ``content`` -- the content to include in the HTML file.
f5650:c0:m3
def _epub_to_mobi(<EOL>self,<EOL>epubPath,<EOL>deleteEpub=False):
self.log.debug('<STR_LIT>')<EOL>mobi = epubPath.replace("<STR_LIT>", "<STR_LIT>")<EOL>kindlegen = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals(<EOL>)<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>try:<EOL><INDENT>with open(mobi):<EOL><INDENT>pass<EOL><DEDENT>fileExists = True<EOL><DEDENT>except IOError:<EOL><INDENT>fileExists = False<EOL>self.log.error(<EOL>"<STR_LIT>" % (mobi, stdout))<EOL>return False<EOL><DEDENT>if deleteEpub:<EOL><INDENT>os.remove(epubPath)<EOL><DEDENT>self.log.debug('<STR_LIT>')<EOL>return mobi<EOL>
*convert the give epub to mobi format using kindlegen* **Key Arguments:** - ``epubPath`` -- path to the epub book - ``deleteEpub`` -- delete the epub when mobi is generated. Default *False* **Return:** - ``mobi`` -- the path to the generated mobi book
f5650:c0:m4
def _docx_to_epub(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>if self.footer:<EOL><INDENT>footer = self._tmp_html_file(self.footer)<EOL>footer = '<STR_LIT>' % locals()<EOL><DEDENT>else:<EOL><INDENT>footer = "<STR_LIT>"<EOL><DEDENT>if self.header:<EOL><INDENT>header = self._tmp_html_file(self.header)<EOL>header = '<STR_LIT>' % locals()<EOL><DEDENT>else:<EOL><INDENT>header = "<STR_LIT>"<EOL><DEDENT>docx = self.urlOrPath<EOL>if self.title:<EOL><INDENT>title = self.title.replace("<STR_LIT>", "<STR_LIT>")<EOL>html = "<STR_LIT>" + self.title.replace("<STR_LIT>", "<STR_LIT>") + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>title = os.path.basename(docx).replace(<EOL>"<STR_LIT>", "<STR_LIT>").replace("<STR_LIT:_>", "<STR_LIT:U+0020>")<EOL>html = "<STR_LIT>" + os.path.basename(docx).replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>pandoc = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>now = datetime.now()<EOL>now = now.strftime("<STR_LIT>")<EOL>imageDir = "<STR_LIT>" % locals()<EOL>if not os.path.exists(imageDir):<EOL><INDENT>os.makedirs(imageDir)<EOL><DEDENT>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>try:<EOL><INDENT>with open(html):<EOL><INDENT>pass<EOL><DEDENT>fileExists = True<EOL><DEDENT>except IOError:<EOL><INDENT>fileExists = False<EOL>self.log.error(<EOL>"<STR_LIT>" % (html, stderr))<EOL>try:<EOL><INDENT>shutil.rmtree(imageDir)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return None<EOL><DEDENT>if fileExists:<EOL><INDENT>if self.outputDirectory:<EOL><INDENT>epub = self.outputDirectory + "<STR_LIT:/>" +os.path.basename(html).replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>epub = docx.replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>pandoc = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals(<EOL>)<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>try:<EOL><INDENT>shutil.rmtree(imageDir)<EOL>os.remove(html)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>with open(epub):<EOL><INDENT>pass<EOL><DEDENT>fileExists = True<EOL><DEDENT>except IOError:<EOL><INDENT>fileExists = False<EOL>self.log.error(<EOL>"<STR_LIT>" % (epub, stderr))<EOL>return None<EOL><DEDENT><DEDENT>self.log.debug('<STR_LIT>')<EOL>return epub<EOL>
*convert docx file to epub*
f5650:c0:m5
def create(self, url, pathToWebarchive):
self.log.debug('<STR_LIT>')<EOL>from subprocess import Popen, PIPE, STDOUT<EOL>webarchiver = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>if len(stderr) == <NUM_LIT:0>:<EOL><INDENT>webarchive = pathToWebarchive<EOL><DEDENT>else:<EOL><INDENT>self.log.error(<EOL>"<STR_LIT>" % locals())<EOL>return -<NUM_LIT:1><EOL><DEDENT>self.log.debug('<STR_LIT>')<EOL>return webarchive<EOL>
*create the webarchive object* **Key Arguments:** - ``url`` -- the url of the webpage to generate the webarchive for - ``pathToWebarchive`` -- tthe path to output the the webarchive file to **Return:** - ``webarchive`` -- the path to the webarchive (or -1 if the generation fails) **Usage:** See class docstring for usage
f5651:c0:m1
def clean(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>url = self.url<EOL>parser_response = self._request_parsed_article_from_mercury(url)<EOL>if "<STR_LIT>" in str(parser_response):<EOL><INDENT>return None<EOL><DEDENT>article = parser_response.json()<EOL>if not article:<EOL><INDENT>return None<EOL><DEDENT>if self.style:<EOL><INDENT>moduleDirectory = os.path.dirname(__file__)<EOL>cssFile = moduleDirectory + "<STR_LIT>"<EOL>pathToReadFile = cssFile<EOL>readFile = codecs.open(pathToReadFile, encoding='<STR_LIT:utf-8>', mode='<STR_LIT:r>')<EOL>thisCss = readFile.read()<EOL>readFile.close()<EOL><DEDENT>else:<EOL><INDENT>thisCss = "<STR_LIT>"<EOL><DEDENT>if "<STR_LIT:error>" in article and article["<STR_LIT:error>"] == True:<EOL><INDENT>print(url)<EOL>print("<STR_LIT:U+0020>" + article["<STR_LIT>"])<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>text = article["<STR_LIT:content>"]<EOL><DEDENT>except:<EOL><INDENT>print("<STR_LIT>" % locals())<EOL>return None<EOL><DEDENT>regex = re.compile(<EOL>'<STR_LIT>')<EOL>text = regex.sub("<STR_LIT>", text)<EOL>regex2 = re.compile(<EOL>'<STR_LIT>', re.I)<EOL>text = regex2.sub("<STR_LIT>", text)<EOL>regex2 = re.compile(<EOL>'<STR_LIT>', re.I)<EOL>text = regex2.sub('<STR_LIT>', text)<EOL>regex = re.compile(<EOL>'<STR_LIT>')<EOL>text = regex.sub("<STR_LIT>", text)<EOL>if self.title == False:<EOL><INDENT>title = article["<STR_LIT:title>"].encode("<STR_LIT:utf-8>", "<STR_LIT:ignore>")<EOL>title = title.decode("<STR_LIT:utf-8>")<EOL>title = title.encode("<STR_LIT:ascii>", "<STR_LIT:ignore>")<EOL>rstrings = """<STR_LIT>"""<EOL>for i in rstrings:<EOL><INDENT>title = title.replace(i, "<STR_LIT>")<EOL><DEDENT>if len(title) == <NUM_LIT:0>:<EOL><INDENT>from datetime import datetime, date, time<EOL>now = datetime.now()<EOL>title = now.strftime("<STR_LIT>")<EOL><DEDENT>self.title = title<EOL><DEDENT>title = self.title.replace("<STR_LIT>", "<STR_LIT>")<EOL>pageTitle = title.replace("<STR_LIT:_>", "<STR_LIT:U+0020>")<EOL>filePath = self.outputDirectory + "<STR_LIT:/>" + title + "<STR_LIT>"<EOL>writeFile = codecs.open(<EOL>filePath, encoding='<STR_LIT:utf-8>', mode='<STR_LIT:w>')<EOL>if self.metadata:<EOL><INDENT>metadata = "<STR_LIT>" % locals()<EOL><DEDENT>else:<EOL><INDENT>metadata = "<STR_LIT>"<EOL><DEDENT>if self.h1:<EOL><INDENT>h1 = "<STR_LIT>" % locals()<EOL><DEDENT>else:<EOL><INDENT>h1 = "<STR_LIT>"<EOL><DEDENT>content =
*parse and clean the html document with Mercury Parser* **Return:** - ``filePath`` -- path to the cleaned HTML document **Usage:** See class usage
f5652:c0:m1
def _request_parsed_article_from_mercury(<EOL>self,<EOL>url):
self.log.debug(<EOL>'<STR_LIT>')<EOL>try:<EOL><INDENT>response = requests.get(<EOL>url="<STR_LIT>",<EOL>params={<EOL>"<STR_LIT:url>": url,<EOL>},<EOL>headers={<EOL>"<STR_LIT>": self.settings["<STR_LIT>"],<EOL>},<EOL>)<EOL><DEDENT>except requests.exceptions.RequestException:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>self.log.debug(<EOL>'<STR_LIT>')<EOL>return response<EOL>
* request parsed article from mercury* **Key Arguments:** - ``url`` -- the URL to the HTML page to parse and clean **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - update package tutorial if needed .. code-block:: python usage code
f5652:c0:m2
def getpackagepath():
moduleDirectory = os.path.dirname(__file__)<EOL>packagePath = os.path.dirname(__file__) + "<STR_LIT>"<EOL>return packagePath<EOL>
*Get the root path for this python package* *Used in unit testing code*
f5653:m0
def main(arguments=None):
<EOL>su = tools(<EOL>arguments=arguments,<EOL>docString=__doc__,<EOL>logLevel="<STR_LIT>",<EOL>options_first=False,<EOL>projectName="<STR_LIT>"<EOL>)<EOL>arguments, settings, log, dbConn = su.setup()<EOL>for arg, val in arguments.iteritems():<EOL><INDENT>if arg[<NUM_LIT:0>] == "<STR_LIT:->":<EOL><INDENT>varname = arg.replace("<STR_LIT:->", "<STR_LIT>") + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>varname = arg.replace("<STR_LIT:<>", "<STR_LIT>").replace("<STR_LIT:>>", "<STR_LIT>")<EOL><DEDENT>if isinstance(val, str) or isinstance(val, unicode):<EOL><INDENT>exec(varname + "<STR_LIT>" % (val,))<EOL><DEDENT>else:<EOL><INDENT>exec(varname + "<STR_LIT>" % (val,))<EOL><DEDENT>if arg == "<STR_LIT>":<EOL><INDENT>dbConn = val<EOL><DEDENT>log.debug('<STR_LIT>' % (varname, val,))<EOL><DEDENT>startTime = times.get_now_sql_datetime()<EOL>log.info(<EOL>'<STR_LIT>' %<EOL>(startTime,))<EOL>if not destinationFolder:<EOL><INDENT>destinationFolder = os.getcwd()<EOL><DEDENT>if not filenameFlag:<EOL><INDENT>filenameFlag = False<EOL><DEDENT>if not cleanFlag:<EOL><INDENT>readability = False<EOL><DEDENT>else:<EOL><INDENT>readability = True<EOL><DEDENT>if init:<EOL><INDENT>from os.path import expanduser<EOL>home = expanduser("<STR_LIT>")<EOL>filepath = home + "<STR_LIT>"<EOL>try:<EOL><INDENT>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if pdf and url:<EOL><INDENT>filepath = printpdf.printpdf(<EOL>log=log,<EOL>settings=settings,<EOL>url=url,<EOL>folderpath=destinationFolder,<EOL>title=filenameFlag,<EOL>append=False,<EOL>readability=readability<EOL>).get()<EOL><DEDENT>if html and url:<EOL><INDENT>cleaner = htmlCleaner.htmlCleaner(<EOL>log=log,<EOL>settings=settings,<EOL>url=url,<EOL>outputDirectory=destinationFolder,<EOL>title=filenameFlag, <EOL>style=cleanFlag, <EOL>metadata=True, <EOL>h1=True <EOL>)<EOL>filepath = cleaner.clean()<EOL><DEDENT>if epub:<EOL><INDENT>if url:<EOL><INDENT>iinput = url<EOL><DEDENT>else:<EOL><INDENT>iinput = docx<EOL><DEDENT>from polyglot import ebook<EOL>epub = ebook(<EOL>log=log,<EOL>settings=settings,<EOL>urlOrPath=iinput,<EOL>title=filenameFlag,<EOL>bookFormat="<STR_LIT>",<EOL>outputDirectory=destinationFolder<EOL>)<EOL>filepath = epub.get()<EOL><DEDENT>if mobi:<EOL><INDENT>if url:<EOL><INDENT>iinput = url<EOL><DEDENT>else:<EOL><INDENT>iinput = docx<EOL><DEDENT>from polyglot import ebook<EOL>mobi = ebook(<EOL>log=log,<EOL>settings=settings,<EOL>urlOrPath=iinput,<EOL>title=filenameFlag,<EOL>bookFormat="<STR_LIT>",<EOL>outputDirectory=destinationFolder,<EOL>)<EOL>filepath = mobi.get()<EOL><DEDENT>if kindle:<EOL><INDENT>if url:<EOL><INDENT>iinput = url<EOL><DEDENT>else:<EOL><INDENT>iinput = docx<EOL><DEDENT>from polyglot import kindle<EOL>sender = kindle(<EOL>log=log,<EOL>settings=settings,<EOL>urlOrPath=iinput,<EOL>title=filenameFlag<EOL>)<EOL>success = sender.send()<EOL><DEDENT>if kindleNB2MD:<EOL><INDENT>basename = os.path.basename(notebook)<EOL>extension = os.path.splitext(basename)[<NUM_LIT:1>]<EOL>filenameNoExtension = os.path.splitext(basename)[<NUM_LIT:0>]<EOL>if destinationFolder:<EOL><INDENT>filepath = destinationFolder + "<STR_LIT:/>" + filenameNoExtension + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>filepath = notebook.replace("<STR_LIT:.>" + extension, "<STR_LIT>")<EOL><DEDENT>from polyglot.markdown import kindle_notebook<EOL>nb = kindle_notebook(<EOL>log=log,<EOL>kindleExportPath=notebook,<EOL>outputPath=filepath<EOL>)<EOL>nb.convert()<EOL><DEDENT>if openFlag:<EOL><INDENT>try:<EOL><INDENT>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if "<STR_LIT>" in locals() and dbConn:<EOL><INDENT>dbConn.commit()<EOL>dbConn.close()<EOL><DEDENT>endTime = times.get_now_sql_datetime()<EOL>runningTime = times.calculate_time_difference(startTime, endTime)<EOL>log.info('<STR_LIT>' %<EOL>(endTime, runningTime, ))<EOL>return<EOL>
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
f5654:m0
def get(self):
self.log.debug('<STR_LIT>')<EOL>if not self.append:<EOL><INDENT>self.append = "<STR_LIT>"<EOL><DEDENT>if not self.readability:<EOL><INDENT>pdfPath = self._print_original_webpage()<EOL><DEDENT>else:<EOL><INDENT>pdfPath = self._print_parsed_webpage()<EOL><DEDENT>tag(<EOL>log=self.log,<EOL>filepath=pdfPath,<EOL>tags="<STR_LIT>",<EOL>rating=<NUM_LIT:2>,<EOL>wherefrom=self.url<EOL>)<EOL>self.log.debug('<STR_LIT>')<EOL>return pdfPath<EOL>
*get the PDF* **Return:** - ``pdfPath`` -- the path to the generated PDF
f5655:c0:m1
def _print_original_webpage(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>if not self.title:<EOL><INDENT>r = requests.get(self.url)<EOL>title = bs4.BeautifulSoup(r.text).title.text<EOL>print(title)<EOL><DEDENT>else:<EOL><INDENT>title = self.title<EOL><DEDENT>url = self.url<EOL>pdfPath = self.folderpath + "<STR_LIT:/>" + title + self.append + "<STR_LIT>"<EOL>electron = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>self.log.debug('<STR_LIT>' % locals())<EOL>if len(stderr):<EOL><INDENT>print(stderr)<EOL><DEDENT>exists = os.path.exists(pdfPath)<EOL>if not exists:<EOL><INDENT>print("<STR_LIT>" % locals())<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>self.log.debug('<STR_LIT>')<EOL>return pdfPath<EOL>
*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
f5655:c0:m2
def _print_parsed_webpage(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>from polyglot import htmlCleaner<EOL>cleaner = htmlCleaner(<EOL>log=self.log,<EOL>settings=self.settings,<EOL>url=self.url,<EOL>outputDirectory=self.folderpath,<EOL>title=self.title, <EOL>style=True, <EOL>metadata=True, <EOL>h1=True <EOL>)<EOL>htmlFile = cleaner.clean()<EOL>if not htmlFile:<EOL><INDENT>return<EOL><DEDENT>pdfPath = htmlFile.replace("<STR_LIT>", self.append + "<STR_LIT>")<EOL>electron = self.settings["<STR_LIT>"]["<STR_LIT>"]<EOL>cmd = """<STR_LIT>""" % locals()<EOL>p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)<EOL>stdout, stderr = p.communicate()<EOL>if len(stderr):<EOL><INDENT>print(stderr)<EOL><DEDENT>self.log.debug('<STR_LIT>' % locals())<EOL>os.remove(htmlFile)<EOL>exists = os.path.exists(pdfPath)<EOL>if not exists:<EOL><INDENT>print("<STR_LIT>" % locals())<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>self.log.debug('<STR_LIT>')<EOL>return pdfPath<EOL>
*print the parsed/cleaned webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
f5655:c0:m3
def send(<EOL>self):
self.log.debug('<STR_LIT>')<EOL>if self.urlOrPath.split("<STR_LIT:.>")[-<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>if self.title:<EOL><INDENT>pathToMobi = self.outputDirectory + "<STR_LIT:/>" + self.title + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>pathToMobi = self.outputDirectory + "<STR_LIT:/>" +os.path.basename(self.urlOrPath)<EOL><DEDENT>shutil.copyfile(self.urlOrPath, pathToMobi)<EOL><DEDENT>else:<EOL><INDENT>pathToMobi = self.get()<EOL>if not pathToMobi:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT><DEDENT>msg = MIMEMultipart()<EOL>msg['<STR_LIT>'] = self.settings["<STR_LIT:email>"]["<STR_LIT>"]<EOL>msg['<STR_LIT>'] = "<STR_LIT:U+002CU+0020>".join(self.settings["<STR_LIT:email>"]["<STR_LIT>"])<EOL>msg['<STR_LIT>'] = '<STR_LIT>'<EOL>text = '<STR_LIT>'<EOL>msg.attach(MIMEText(text))<EOL>basename = os.path.basename(pathToMobi)<EOL>print("<STR_LIT>" % locals())<EOL>msg.attach(self.get_attachment(pathToMobi))<EOL>fp = StringIO()<EOL>gen = Generator(fp, mangle_from_=False)<EOL>gen.flatten(msg)<EOL>msg = fp.getvalue()<EOL>try:<EOL><INDENT>mail_server = smtplib.SMTP_SSL(host=self.settings["<STR_LIT:email>"]["<STR_LIT>"],<EOL>port=self.settings["<STR_LIT:email>"]["<STR_LIT>"])<EOL>mail_server.login(self.settings["<STR_LIT:email>"]["<STR_LIT>"], self.settings[<EOL>"<STR_LIT:email>"]["<STR_LIT>"])<EOL>mail_server.sendmail(self.settings["<STR_LIT:email>"]["<STR_LIT>"], "<STR_LIT:U+002CU+0020>".join(self.settings[<EOL>"<STR_LIT:email>"]["<STR_LIT>"]), msg)<EOL>mail_server.close()<EOL><DEDENT>except smtplib.SMTPException:<EOL><INDENT>os.remove(pathToMobi)<EOL>self.log.error(<EOL>'<STR_LIT>')<EOL>return False<EOL><DEDENT>os.remove(pathToMobi)<EOL>self.log.debug('<STR_LIT>')<EOL>return True<EOL>
*send the mobi book generated to kindle email address(es)* **Return:** - ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es).
f5659:c0:m1
def get_attachment(self, file_path):
try:<EOL><INDENT>file_ = open(file_path, '<STR_LIT:rb>')<EOL>attachment = MIMEBase('<STR_LIT>', '<STR_LIT>')<EOL>attachment.set_payload(file_.read())<EOL>file_.close()<EOL>encoders.encode_base64(attachment)<EOL>attachment.add_header('<STR_LIT>', '<STR_LIT>',<EOL>filename=os.path.basename(file_path))<EOL>return attachment<EOL><DEDENT>except IOError:<EOL><INDENT>traceback.print_exc()<EOL>message = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>print(message, file=sys.stderr)<EOL>sys.exit(<NUM_LIT:6>)<EOL><DEDENT>
Get file as MIMEBase message
f5659:c0:m2
def convert(self):
self.log.debug('<STR_LIT>')<EOL>import codecs<EOL>pathToReadFile = self.kindleExportPath<EOL>try:<EOL><INDENT>self.log.debug("<STR_LIT>" %<EOL>(pathToReadFile,))<EOL>readFile = codecs.open(pathToReadFile, encoding='<STR_LIT:utf-8>', mode='<STR_LIT:r>')<EOL>annotations = readFile.read()<EOL>readFile.close()<EOL><DEDENT>except IOError as e:<EOL><INDENT>message = '<STR_LIT>' % (pathToReadFile,)<EOL>self.log.critical(message)<EOL>raise IOError(message)<EOL><DEDENT>annotations = annotations.replace("<STR_LIT>", "<STR_LIT:'>").replace(<EOL>"<STR_LIT>", '<STR_LIT:">').replace("<STR_LIT>", '<STR_LIT:">').replace("<STR_LIT>", '<STR_LIT:">').replace("<STR_LIT>", "<STR_LIT:->").replace("<STR_LIT>", "<STR_LIT:->")<EOL>try:<EOL><INDENT>title = self.find_component("<STR_LIT>", annotations)<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>regex = re.compile(r'<STR_LIT>')<EOL>title = regex.sub("<STR_LIT>", title)<EOL>authors = self.find_component("<STR_LIT>", annotations)<EOL>citation = self.find_component("<STR_LIT>", annotations)<EOL>regex = re.compile(r'<STR_LIT>', re.S)<EOL>citation = regex.sub('<STR_LIT:*>', citation)<EOL>regex = re.compile(r'<STR_LIT>', re.S)<EOL>citation = regex.sub('<STR_LIT>', citation).replace("<STR_LIT>", "<STR_LIT>")<EOL>annotationDict = {}<EOL>matchObject = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>annotations,<EOL>flags=re.S<EOL>)<EOL>for match in matchObject:<EOL><INDENT>location = int(match.group("<STR_LIT:location>"))<EOL>location = "<STR_LIT>" % locals()<EOL>if match.group("<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>annotationDict[location] = {"<STR_LIT>": match.group("<STR_LIT>"), "<STR_LIT>": match.group(<EOL>"<STR_LIT>"), "<STR_LIT>": self.clean(match.group("<STR_LIT>"))[<NUM_LIT:3>:-<NUM_LIT:2>], "<STR_LIT>": self.clean(match.group("<STR_LIT>"))}<EOL><DEDENT>except:<EOL><INDENT>print(match.group("<STR_LIT>"))<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>annotationDict[location] = {"<STR_LIT>": match.group(<EOL>"<STR_LIT>"), "<STR_LIT>": self.clean(match.group("<STR_LIT>"))}<EOL><DEDENT>except:<EOL><INDENT>print(match.group("<STR_LIT>"))<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT><DEDENT><DEDENT>matchObject = re.finditer(<EOL>r"""<STR_LIT>""",<EOL>annotations,<EOL>flags=re.S<EOL>)<EOL>for match in matchObject:<EOL><INDENT>location = int(match.group("<STR_LIT:location>"))<EOL>location = "<STR_LIT>" % locals()<EOL>if match.group("<STR_LIT>"):<EOL><INDENT>annotationDict[location] = {"<STR_LIT>": None, "<STR_LIT>": match.group(<EOL>"<STR_LIT>"), "<STR_LIT>": self.clean(match.group("<STR_LIT>"))}<EOL><DEDENT>else:<EOL><INDENT>annotationDict[location] = {<EOL>"<STR_LIT>": None, "<STR_LIT>": self.clean(match.group("<STR_LIT>"))}<EOL><DEDENT><DEDENT>annotationDict = collections.OrderedDict(<EOL>sorted(annotationDict.items()))<EOL>mdContent = "<STR_LIT>" % locals()<EOL>for k, v in annotationDict.items():<EOL><INDENT>mdContent += self.convertToMD(v) + "<STR_LIT>"<EOL><DEDENT>if len(annotationDict) == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>pathToWriteFile = self.outputPath<EOL>try:<EOL><INDENT>self.log.debug("<STR_LIT>" %<EOL>(pathToWriteFile,))<EOL>writeFile = codecs.open(<EOL>pathToWriteFile, encoding='<STR_LIT:utf-8>', mode='<STR_LIT:w>')<EOL><DEDENT>except IOError as e:<EOL><INDENT>message = '<STR_LIT>' % (pathToWriteFile,)<EOL>self.log.critical(message)<EOL>raise IOError(message)<EOL><DEDENT>writeFile.write(mdContent)<EOL>writeFile.close()<EOL>self.log.debug('<STR_LIT>')<EOL>return pathToWriteFile<EOL>
*convert the kindle_notebook object* **Return:** - ``kindle_notebook`` **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - update the package tutorial if needed .. code-block:: python usage code
f5660:c0:m1
def bold(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to MMD bolded text* **Key Arguments:** - ``text`` -- the text to convert to MMD bold **Return:** - ``text`` -- the bolded text **Usage:** To convert a text block to bolded text: .. code-block:: python text = md.bold(" nice day! ") print text # OUTPUT: **nice day!**
f5664:c0:m1
def em(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT:_>", "<STR_LIT:_>")<EOL>
*convert plain-text to MMD italicised text* **Key Arguments:** - ``text`` -- the text to convert to MMD italics **Return:** - ``text`` -- the emphasised text **Usage:** To convert a text block to emphasised text: .. code-block:: python text = md.em(" nice day! ") print text # OUTPUT: _nice day!_
f5664:c0:m2
def underline(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to HTML underline text* **Key Arguments:** - ``text`` -- the text to convert to HTML underlined **Return:** - ``text`` -- the underlined text **Usage:** To convert a text block to underlined text: .. code-block:: python text = md.underline(" nice day! ") print text # OUTPUT: <u>nice day!</u>
f5664:c0:m3
def strike(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to HTML strike-through text* **Key Arguments:** - ``text`` -- the text to convert to HTML strike-through **Return:** - ``text`` -- the strike-through text **Usage:** To convert a text block to strike-through text: .. code-block:: python text = md.strike(" nice day! ") print text # OUTPUT: <s>nice day!</s>
f5664:c0:m4
def hl(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to MMD critical markup highlighted text* **Key Arguments:** - ``text`` -- the text to convert to MMD highlighted text **Return:** - ``text`` -- the highlighted text **Usage:** To convert a text block to highlighted text: .. code-block:: python text = md.hl(" nice day! ") print text # OUTPUT: {==nice day!==}
f5664:c0:m5
def code(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to MMD inline-code text* **Key Arguments:** - ``text`` -- the text to convert to MMD inline-code text **Return:** - ``text`` -- the inline-code text **Usage:** To convert a text block to inline-code text: .. code-block:: python text = md.code(" nice day! ") print text # OUTPUT: `nice day!`
f5664:c0:m6
def comment(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to MMD comment* **Key Arguments:** - ``text`` -- the text to convert to MMD comment **Return:** - ``text`` -- the comment text **Usage:** To convert a text block to comment text: .. code-block:: python text = md.comment(" nice day! ") print text # OUTPUT: {>>nice day!<<}
f5664:c0:m7
def footnote(<EOL>self,<EOL>text):
rand = str(randint(<NUM_LIT:0>, <NUM_LIT>))<EOL>now = datetime.now()<EOL>now = now.strftime("<STR_LIT>") + rand<EOL>text = text.strip()<EOL>regex = re.compile(r'<STR_LIT>')<EOL>text = regex.sub("<STR_LIT>", text)<EOL>return "<STR_LIT>" % locals()<EOL>
*convert plain-text to MMD footnote* **Key Arguments:** - ``text`` -- the text to convert to MMD footnote **Return:** - ``text`` -- the footnote text **Usage:** To convert a text block to footnote text: .. code-block:: python text = md.footnote(" nice day! ") print text # OUTPUT: [^20170228T21:57:40-99] # # [^20170228T21:57:40-99]: nice day!
f5664:c0:m8
def glossary(<EOL>self,<EOL>term,<EOL>definition):
term = term.strip()<EOL>term = term.lower()<EOL>title = term.title()<EOL>definition = definition.strip()<EOL>regex = re.compile(r'<STR_LIT>')<EOL>definition = regex.sub("<STR_LIT>", definition)<EOL>return "<STR_LIT>" % locals()<EOL>
*genarate a MMD glossary* **Key Arguments:** - ``term`` -- the term to add as a glossary item - ``definition`` -- the definition of the glossary term **Return:** - ``glossary`` -- the glossary text **Usage:** To genarate a glossary item: .. code-block:: python text = \"\"\"Pomaceous fruit of plants of the genus Malus in the family Rosaceae. Also the makers of really great products.\"\"\" definition = md.glossary("Apple", text) print definition # OUTPUT: # [^apple] # # [^apple]: Apple # Pomaceous fruit of plants of the genus Malus in the family Rosaceae. # Also the makers of really great products.
f5664:c0:m9
def cite(<EOL>self,<EOL>title,<EOL>author=False,<EOL>year=False,<EOL>url=False,<EOL>publisher=False,<EOL>mediaKind=False,<EOL>linkedText=False,<EOL>nocite=False):
rand = str(randint(<NUM_LIT:0>, <NUM_LIT:100>))<EOL>anchor = title.replace("<STR_LIT:U+0020>", "<STR_LIT>").lower()<EOL>title = title.title()<EOL>citation = "<STR_LIT>"<EOL>if author:<EOL><INDENT>author = author.title() + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>author = "<STR_LIT>"<EOL><DEDENT>if title[-<NUM_LIT:1>] == "<STR_LIT:.>":<EOL><INDENT>title = title[:-<NUM_LIT:1>]<EOL><DEDENT>if url:<EOL><INDENT>title = "<STR_LIT>" % locals()<EOL><DEDENT>else:<EOL><INDENT>title = "<STR_LIT>" % locals()<EOL><DEDENT>if publisher and year:<EOL><INDENT>publisher = "<STR_LIT>" % locals()<EOL><DEDENT>elif publisher:<EOL><INDENT>publisher = "<STR_LIT>" % locals()<EOL><DEDENT>elif year:<EOL><INDENT>publisher = "<STR_LIT>" % locals()<EOL><DEDENT>else:<EOL><INDENT>publisher = "<STR_LIT>"<EOL><DEDENT>if mediaKind:<EOL><INDENT>mediaKind = "<STR_LIT>" % locals()<EOL>mediaKind = mediaKind.lower()<EOL><DEDENT>else:<EOL><INDENT>mediaKind = "<STR_LIT>"<EOL><DEDENT>if not linkedText:<EOL><INDENT>linkedText = "<STR_LIT>"<EOL><DEDENT>if nocite:<EOL><INDENT>linkedText = "<STR_LIT>"<EOL><DEDENT>return "<STR_LIT>" % locals()<EOL>
*generate a MMD citation* **Key Arguments:** - ``title`` -- the citation title - ``author`` -- the author. Default *False* - ``year`` -- year published. Default *False* - ``url`` -- url to the media. Default *False* - ``publisher`` -- the publisher of the media. Default *False* - ``mediaKind`` -- what kind of media is it?. Default *False* - ``linkedText`` -- the text to link to the citation. Default *False/blank* - ``nocite`` -- a give citation that has no reference in main doc **Return:** - ``citation`` -- the MMD citation **Usage:** To generate a MMD citation: .. code-block:: python citation = md.cite( title="A very good book", author="John Doe", year=2015, url="http://www.thespacedoctor.co.uk", publisher="Beefy Books", mediaKind=False, linkedText="Doe 2015") print citation # OUTPUT: [Doe 2015][#averygoodbook90] # # [#averygoodbook90]: John Doe. *[A Very Good Book](http://www.thespacedoctor.co.uk)*. Beefy Books, 2015.
f5664:c0:m10
def url(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT:<>", "<STR_LIT:>>")<EOL>
*convert plain-text to MMD clickable URL* **Key Arguments:** - ``text`` -- the text to convert to MMD clickable URL **Return:** - ``text`` -- the URL text **Usage:** To convert a text block to MMD clickable URL: .. code-block:: python text = md.url(" http://www.google.com ") print text # OUTPUT: <http://www.google.com>
f5664:c0:m11
def math_inline(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT:$>", "<STR_LIT:$>")<EOL>
*convert plain-text to MMD inline math* **Key Arguments:** - ``text`` -- the text to convert to MMD inline math **Return:** - ``math`` -- the inline math text **Usage:** To convert a text to MMD inline math: .. code-block:: python text = md.math_inline("{e}^{i\pi }+1=0") print text # OUTPUT: ${e}^{i\pi }+1=0$
f5664:c0:m12
def math_block(<EOL>self,<EOL>text):
return self._surround(text, "<STR_LIT>", "<STR_LIT>")<EOL>
*convert plain-text to MMD math block* **Key Arguments:** - ``text`` -- the text to convert to MMD math block **Return:** - ``math`` -- the math block text **Usage:** To convert a text to MMD math block: .. code-block:: python text = md.math_inline("{e}^{i\pi }+1=0") print text # OUTPUT: $${e}^{i\pi }+1=0$$
f5664:c0:m13
def header(<EOL>self,<EOL>text,<EOL>level):
m = self.reWS.match(text)<EOL>prefix = m.group(<NUM_LIT:1>)<EOL>text = m.group(<NUM_LIT:2>)<EOL>suffix = m.group(<NUM_LIT:3>)<EOL>return "<STR_LIT:#>" * level + "<STR_LIT>" % locals()<EOL>
*convert plain-text to MMD header* **Key Arguments:** - ``text`` -- the text to convert to MMD header - ``level`` -- the header level to convert the text to **Return:** - ``header`` -- the MMD header **Usage:** To convert a text MMD header: .. code-block:: python header = md.header(" This is my header ", level=3) print header # OUTPUT: # ### This is my header #
f5664:c0:m14
def definition(<EOL>self,<EOL>text,<EOL>definition):
text = text.strip()<EOL>definition = definition.strip()<EOL>regex = re.compile(r'<STR_LIT>')<EOL>definition = regex.sub("<STR_LIT>", definition)<EOL>return "<STR_LIT>" % locals()<EOL>
*genarate a MMD definition* **Key Arguments:** - ``text`` -- the text to define - ``definition`` -- the definition **Return:** - ``definition`` -- the MMD style definition **Usage:** To genarate a MMD definition: .. code-block:: python text = \"\"\"Pomaceous fruit of plants of the genus Malus in the family Rosaceae. Also the makers of really great products.\"\"\" definition = md.definition("Apple", text) print definition # OUTPUT: # Apple # : Pomaceous fruit of plants of the genus Malus in the family Rosaceae. # Also the makers of really great products. #
f5664:c0:m15
def headerLink(<EOL>self,<EOL>headerText,<EOL>text=False):
headerText = headerText.strip()<EOL>if text:<EOL><INDENT>return self._surround(text, "<STR_LIT:[>", "<STR_LIT>" % locals())<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % locals()<EOL><DEDENT>
*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - ``link`` -- the link to the header **Usage:** To generate a MMD header link: .. code-block:: python link = md.headerLink(" This is my header ", "inline text") print link # OUTPUT: # [inline text][This is my header] #
f5664:c0:m16
def image(<EOL>self,<EOL>url,<EOL>title="<STR_LIT>",<EOL>width=<NUM_LIT>):
title = title.strip()<EOL>caption = title<EOL>now = datetime.now()<EOL>figId = now.strftime("<STR_LIT>")<EOL>if len(title):<EOL><INDENT>figId = "<STR_LIT>" % locals()<EOL><DEDENT>imageLink = """<STR_LIT>""" % locals()<EOL>return imageLink<EOL>
*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* **Return:** - ``imageLink`` -- the MMD image link **Usage:** To create a MMD image link: .. code-block:: python imageLink = md.image( "http://www.thespacedoctor.co.uk/images/thespacedoctor_icon_white_circle.png", "thespacedoctor icon", 400) print imageLink # OUTPUT: # ![thespacedoctor icon][thespacedoctor icon 20170228t130146.472262] # # [thespacedoctor icon 20170228t130146.472262]: http://www.thespacedoctor.co.uk/images/thespacedoctor_icon_white_circle.png "thespacedoctor icon" width=400px #
f5664:c0:m17
def blockquote(<EOL>self,<EOL>text):
m = self.reWS.match(text)<EOL>return "<STR_LIT>" + ("<STR_LIT>").join(m.group(<NUM_LIT:2>).split("<STR_LIT:\n>")) + "<STR_LIT>"<EOL>
*convert plain-text to MMD blockquote* **Key Arguments:** - ``text`` -- the text to convert to MMD blockquote **Return:** - ``blockquote`` -- the MMD blockquote **Usage:** To convert a text to a MMD blockquote: .. code-block:: python text = md.quote(" This is my quote ") print text # OUTPUT: # > This is my quote #
f5664:c0:m18
def ul(<EOL>self,<EOL>text):
m = self.reWS.match(text)<EOL>ul = []<EOL>for l in m.group(<NUM_LIT:2>).split("<STR_LIT:\n>"):<EOL><INDENT>prefix, text, suffix = self._snip_whitespace(l)<EOL>ul.append("<STR_LIT>" % locals())<EOL><DEDENT>return ("<STR_LIT:\n>").join(ul) + "<STR_LIT>"<EOL>
*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD unordered list: .. code-block:: python ul = md.ul(" This is a list item ") print ul # OUTPUT: # * This is a list item #
f5664:c0:m19
def ol(<EOL>self,<EOL>text):
m = self.reWS.match(text)<EOL>ol = []<EOL>for thisIndex, l in enumerate(m.group(<NUM_LIT:2>).split("<STR_LIT:\n>")):<EOL><INDENT>thisIndex += <NUM_LIT:1><EOL>prefix, text, suffix = self._snip_whitespace(l)<EOL>ol.append("<STR_LIT>" % locals())<EOL><DEDENT>return ("<STR_LIT:\n>").join(ol) + "<STR_LIT>"<EOL>
*convert plain-text to MMD ordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD ordered list **Return:** - ``ol`` -- the MMD ordered list **Usage:** To convert text to MMD ordered list: .. code-block:: python ol = md.ol(" This is a list item ") print ol # OUTPUT: # 1. This is a list item #
f5664:c0:m20
def codeblock(<EOL>self,<EOL>text,<EOL>lang="<STR_LIT>"):
reRemoveNewline = re.compile(r'<STR_LIT>', re.S)<EOL>m = reRemoveNewline.match(text)<EOL>text = m.group(<NUM_LIT:2>)<EOL>return "<STR_LIT>" % locals()<EOL>
*convert plain-text to MMD fenced codeblock* **Key Arguments:** - ``text`` -- the text to convert to MMD fenced codeblock - ``lang`` -- the code language for syntax highlighting. Default *''* **Return:** - ``text`` -- the MMD fenced codeblock **Usage:** To convert a text block to comment text: .. code-block:: python text = md.codeblock("def main()", "python") print text # OUTPUT: # ```python # def main() # ```
f5664:c0:m21
def inline_link(<EOL>self,<EOL>text,<EOL>url):
m = self.reWS.match(text)<EOL>prefix = m.group(<NUM_LIT:1>)<EOL>text = m.group(<NUM_LIT:2>)<EOL>suffix = m.group(<NUM_LIT:3>)<EOL>url = url.strip()<EOL>return "<STR_LIT>" % locals()<EOL>
*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** To convert a text and url to MMD link: .. code-block:: python text = md.inline_link( " google search engine ", " http://www.google.com ") print text # OUTPUT: # [google search engine](http://www.google.com)
f5664:c0:m22
def _snip_whitespace(<EOL>self,<EOL>text):
self.log.debug('<STR_LIT>')<EOL>m = self.reWS.match(text)<EOL>prefix = m.group(<NUM_LIT:1>)<EOL>text = m.group(<NUM_LIT:2>)<EOL>suffix = m.group(<NUM_LIT:3>)<EOL>self.log.debug('<STR_LIT>')<EOL>return prefix, text, suffix<EOL>
*snip the whitespace at the start and end of the text* **Key Arguments:** - ``text`` -- the text to snip **Return:** - ``prefix``, ``text``, ``suffix`` -- the starting whitespace, text and endding whitespace
f5664:c0:m23
def _surround(<EOL>self,<EOL>text,<EOL>left,<EOL>right):
self.log.debug('<STR_LIT>')<EOL>prefix, text, suffix = self._snip_whitespace(text)<EOL>text = text.replace("<STR_LIT>", "<STR_LIT>").replace("<STR_LIT>", "<STR_LIT>").replace(<EOL>"<STR_LIT>", "<STR_LIT>").replace("<STR_LIT>", "<STR_LIT>").replace("<STR_LIT>", "<STR_LIT>" % locals())<EOL>text = """<STR_LIT>""" % locals()<EOL>self.log.debug('<STR_LIT>')<EOL>return text<EOL>
*surround text with given characters* **Key Arguments:** - ``text`` -- the text to surround. - ``left`` -- characters to the left of text - ``right`` -- characters to the right of text **Return:** - ``text`` -- the surronded text
f5664:c0:m24
def get_object(model, cid, engine_name=None, connection=None):
from uliweb import settings<EOL>if not id:<EOL><INDENT>return <EOL><DEDENT>if not check_enable():<EOL><INDENT>return<EOL><DEDENT>redis = get_redis()<EOL>if not redis: return<EOL>tablename = model._alias or model.tablename<EOL>info = settings.get_var('<STR_LIT>' % tablename, {})<EOL>if info is None:<EOL><INDENT>return<EOL><DEDENT>_id = get_id(engine_name or model.get_engine_name(), tablename, cid)<EOL>try:<EOL><INDENT>log.debug("<STR_LIT>" % (tablename, _id))<EOL>if redis.exists(_id):<EOL><INDENT>v = redis.hgetall(_id)<EOL>o = model.load(v, from_='<STR_LIT>')<EOL>log.debug("<STR_LIT>")<EOL>return o<EOL><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.exception(e)<EOL><DEDENT>
Get cached object from redis if id is None then return None:
f5705:m5
def set_object(model, instance, fields=None, engine_name=None):
from uliweb import settings<EOL>if not check_enable():<EOL><INDENT>return<EOL><DEDENT>redis = get_redis()<EOL>if not redis: return<EOL>tablename = model._alias or model.tablename<EOL>exclude = []<EOL>if not fields:<EOL><INDENT>fields, exclude = get_fields(tablename)<EOL><DEDENT>v = instance.dump(fields, exclude=exclude)<EOL>info = settings.get_var('<STR_LIT>' % tablename, {})<EOL>if info is None:<EOL><INDENT>return<EOL><DEDENT>expire = settings.get_var('<STR_LIT>', <NUM_LIT:0>)<EOL>key = '<STR_LIT:id>'<EOL>if info and isinstance(info, dict):<EOL><INDENT>expire = info.get('<STR_LIT>', expire)<EOL>key = info.get('<STR_LIT:key>', key)<EOL><DEDENT>if '<STR_LIT:.>' in key or key not in model.properties:<EOL><INDENT>_key = import_attr(key)(instance)<EOL><DEDENT>else:<EOL><INDENT>_key = getattr(instance, key)<EOL><DEDENT>_id = get_id(engine_name or model.get_engine_name(), tablename, _key)<EOL>try:<EOL><INDENT>pipe = redis.pipeline()<EOL>p = pipe.delete(_id).hmset(_id, v)<EOL>expire_msg = '<STR_LIT>'<EOL>if expire:<EOL><INDENT>p = p.expire(_id, expire)<EOL>expire_msg = '<STR_LIT>' % expire<EOL><DEDENT>r = p.execute()<EOL>log.debug("<STR_LIT>" % (tablename, _id, expire_msg))<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.exception(e)<EOL><DEDENT>
Only support simple condition, for example: Model.c.id == n if not id provided, then use instance.id
f5705:m6
def is_allowed(self, filename):
return True<EOL>
Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten.
f5709:c0:m1
def get_redis(**options):
from uliweb import settings<EOL>from uliweb.utils.common import log<EOL>import redis<EOL>options = (options or {})<EOL>options.update(settings.REDIS)<EOL>if '<STR_LIT>' in options:<EOL><INDENT>client = redis.Redis(unix_socket_path=options['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>global __connection_pool__<EOL>if not __connection_pool__ or __connection_pool__[<NUM_LIT:0>] != options['<STR_LIT>']:<EOL><INDENT>d = {'<STR_LIT:host>':'<STR_LIT:localhost>', '<STR_LIT:port>':<NUM_LIT>}<EOL>d.update(options['<STR_LIT>'])<EOL>__connection_pool__ = (d, redis.ConnectionPool(**d))<EOL><DEDENT>client = redis.Redis(connection_pool=__connection_pool__[<NUM_LIT:1>])<EOL><DEDENT>if settings.REDIS.test_first:<EOL><INDENT>try:<EOL><INDENT>client.info()<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.exception(e)<EOL>client = None<EOL><DEDENT><DEDENT>return client<EOL>
if no options defined, then it'll use settings options #unix_socket_path = '/tmp/redis.sock' connection_pool = {'host':'localhost', 'port':6379} #if test after created redis client object test_first = False
f5712:m0
def get_lock(key, value=None, expiry_time=<NUM_LIT>):
from uliweb.utils.common import get_uuid<EOL>redis = get_redis()<EOL>value = value or get_uuid()<EOL>return redis.set(key, value, ex=expiry_time, nx=True)<EOL>
Get a distribute lock
f5712:m1
def set_lock(key, value=None, expiry_time=<NUM_LIT>):
from uliweb.utils.common import get_uuid<EOL>redis = get_redis()<EOL>value = value or get_uuid()<EOL>return redis.set(key, value, ex=expiry_time, xx=True)<EOL>
Force to set a distribute lock
f5712:m2
def after_init_apps(sender):
from uliweb import settings<EOL>from uliweb.utils.common import log<EOL>check = settings.get_var('<STR_LIT>')<EOL>if check:<EOL><INDENT>client = get_redis()<EOL>try:<EOL><INDENT>info = client.info()<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.exception(e)<EOL>log.error('<STR_LIT>')<EOL>return<EOL><DEDENT>redis_version = info['<STR_LIT>']<EOL>version = tuple(map(int, redis_version.split('<STR_LIT:.>')))<EOL>op = re_compare_op.search(check)<EOL>if op:<EOL><INDENT>_op = op.group()<EOL>_v = check[op.end()+<NUM_LIT:1>:].strip()<EOL><DEDENT>else:<EOL><INDENT>_op = '<STR_LIT:=>'<EOL>_v = check<EOL><DEDENT>nv = tuple(map(int, _v.split('<STR_LIT:.>')))<EOL>if _op == '<STR_LIT:=>':<EOL><INDENT>flag = version[:len(nv)] == nv<EOL><DEDENT>elif _op == '<STR_LIT>':<EOL><INDENT>flag = version >= nv<EOL><DEDENT>elif _op == '<STR_LIT:>>':<EOL><INDENT>flag = version > nv<EOL><DEDENT>elif _op == '<STR_LIT>':<EOL><INDENT>flag = version <= nv<EOL><DEDENT>elif _op == '<STR_LIT:<>':<EOL><INDENT>flag = version < nv<EOL><DEDENT>else:<EOL><INDENT>log.error("<STR_LIT>" % _op)<EOL><DEDENT>if not flag:<EOL><INDENT>log.error("<STR_LIT>" % (redis_version, _v))<EOL><DEDENT><DEDENT>
Check redis version
f5712:m3
def cal_position(self, text, has_toplinks, has_bottomlinks, head_len, head_start):
if head_len == <NUM_LIT:0>:<EOL><INDENT>top_start = top_end = bottom_start = bottom_end = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>top_start = top_end = head_start + <NUM_LIT:6><EOL>bottom_start = bottom_end = head_start + head_len - <NUM_LIT:7><EOL><DEDENT>if has_toplinks:<EOL><INDENT>t = r_top.search(text)<EOL>if t:<EOL><INDENT>top_start, top_end = t.span()<EOL><DEDENT><DEDENT>if has_bottomlinks:<EOL><INDENT>t = r_bottom.search(text)<EOL>if t:<EOL><INDENT>bottom_start, bottom_end = t.span()<EOL><DEDENT><DEDENT>return top_end, bottom_end<EOL>
Calculate the position of toplinks and bottomlinks, if there is not toplinks and bottomlinks then toplinks position will be the position after <head> and if there is no bottomlinks, the bottomlinks position will be the position before </head>.
f5713:c2:m4
def init_static_combine():
from uliweb import settings<EOL>from hashlib import md5<EOL>import os<EOL>d = {}<EOL>if settings.get_var('<STR_LIT>', False):<EOL><INDENT>for k, v in settings.get('<STR_LIT>', {}).items():<EOL><INDENT>key = '<STR_LIT>'+md5('<STR_LIT>'.join(v)).hexdigest()+os.path.splitext(v[<NUM_LIT:0>])[<NUM_LIT:1>]<EOL>d[key] = v<EOL><DEDENT><DEDENT>return d<EOL>
Process static combine, create md5 key according each static filename
f5714:m1
def csrf_token():
from uliweb import request, settings<EOL>from uliweb.utils.common import safe_str<EOL>v = {}<EOL>token_name = settings.CSRF.cookie_token_name<EOL>if not request.session.deleted and request.session.get(token_name):<EOL><INDENT>v = request.session[token_name]<EOL>if time.time() >= v['<STR_LIT>'] + v['<STR_LIT>']:<EOL><INDENT>v = {}<EOL><DEDENT>else:<EOL><INDENT>v['<STR_LIT>'] = time.time()<EOL><DEDENT><DEDENT>if not v:<EOL><INDENT>token = request.cookies.get(token_name)<EOL>if not token:<EOL><INDENT>token = uuid.uuid4().get_hex()<EOL><DEDENT>v = {'<STR_LIT>':token, '<STR_LIT>':settings.CSRF.timeout, '<STR_LIT>':time.time()}<EOL><DEDENT>if not request.session.deleted:<EOL><INDENT>request.session[token_name] = v<EOL><DEDENT>return safe_str(v['<STR_LIT>'])<EOL>
Get csrf token or create new one
f5717:m0
def check_csrf_token():
from uliweb import request, settings<EOL>token = (request.params.get(settings.CSRF.form_token_name, None) or<EOL>request.headers.get("<STR_LIT>") or<EOL>request.headers.get("<STR_LIT>"))<EOL>if not token:<EOL><INDENT>raise Forbidden("<STR_LIT>")<EOL><DEDENT>if csrf_token() != token:<EOL><INDENT>raise Forbidden("<STR_LIT>")<EOL><DEDENT>
Check token
f5717:m1
def startup_installed(sender):
import os<EOL>from uliweb.core.SimpleFrame import get_app_dir<EOL>from uliweb.i18n import install, set_default_language<EOL>from uliweb.utils.common import pkg, expand_path<EOL>path = pkg.resource_filename('<STR_LIT>', '<STR_LIT>')<EOL>_dirs = []<EOL>for d in sender.settings.get_var('<STR_LIT>', []):<EOL><INDENT>_dirs.append(expand_path(d))<EOL><DEDENT>localedir = ([os.path.normpath(sender.apps_dir + '<STR_LIT>')] + <EOL>[get_app_dir(appname) for appname in sender.apps] + [path] + _dirs)<EOL>install('<STR_LIT>', localedir)<EOL>set_default_language(sender.settings.I18N.LANGUAGE_CODE)<EOL>
@LANGUAGE_CODE
f5719:m0
def parse_accept_lang_header(lang_string):
result = []<EOL>pieces = accept_language_re.split(lang_string)<EOL>if pieces[-<NUM_LIT:1>]:<EOL><INDENT>return []<EOL><DEDENT>for i in range(<NUM_LIT:0>, len(pieces) - <NUM_LIT:1>, <NUM_LIT:3>):<EOL><INDENT>first, lang, priority = pieces[i : i + <NUM_LIT:3>]<EOL>if first:<EOL><INDENT>return []<EOL><DEDENT>priority = priority and float(priority) or <NUM_LIT:1.0><EOL>result.append((lang, priority))<EOL><DEDENT>result.sort(lambda x, y: -cmp(x[<NUM_LIT:1>], y[<NUM_LIT:1>]))<EOL>return result<EOL>
Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned.
f5720:m1
def process_exception(self, request, e):
if isinstance(e, RedirectException):<EOL><INDENT>response = e.get_response()<EOL>self.process_response(request, response)<EOL><DEDENT>
Still process session data when specially Exception
f5727:c0:m3
def get_cipher(key=None, keyfile=None):
des_func = import_attr(settings.SECRETKEY.CIPHER_CLS)<EOL>kwargs = settings.SECRETKEY.CIPHER_ARGS<EOL>if not key:<EOL><INDENT>key = functions.get_cipher_key(keyfile)<EOL><DEDENT>cipher = des_func(key, **kwargs)<EOL>return cipher<EOL>
Get cipher object, and then you can invoke: des = get_cipher() d = des.encrpy('Hello') print des.descrpy(d)
f5733:m0
def encrypt(v, key=None, keyfile=None):
cipher = functions.get_cipher(key, keyfile)<EOL>return cipher.encrypt(v)<EOL>
Encrypt an string
f5733:m1
def decrypt(v, key=None, keyfile=None):
cipher = functions.get_cipher(key, keyfile)<EOL>return cipher.decrypt(v)<EOL>
Encrypt an string
f5733:m2
def get_key(keyfile=None):
keyfile = keyfile or application_path(settings.SECRETKEY.SECRET_FILE)<EOL>with file(keyfile, '<STR_LIT:rb>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT>
Read the key content from secret_file
f5733:m3
def get_cipher_key(keyfile=None):
_key = get_key(keyfile)<EOL>_k = md5(_key).hexdigest()<EOL>key = xor(_k[:<NUM_LIT:8>], _k[<NUM_LIT:8>:<NUM_LIT:16>], _k[<NUM_LIT:16>:<NUM_LIT>], _k[<NUM_LIT>:])<EOL>return key<EOL>
Create key which will be used in des, because des need 8bytes chars
f5733:m4
def show_table(name, table, i, total):
return '<STR_LIT>' % (i+<NUM_LIT:1>, total, table.__appname__, name)<EOL>
Display table info, name is tablename table is table object i is current Index total is total of tables
f5738:m7
def handle(self, options, global_options, *args):
from uliweb.orm.graph import generate_dot, generate_file<EOL>from uliweb.utils.common import get_tempfilename, get_tempfilename2<EOL>engine = get_engine(options, global_options)<EOL>if args:<EOL><INDENT>apps = args<EOL><DEDENT>else:<EOL><INDENT>apps = self.get_apps(global_options)<EOL><DEDENT>if not options.tables:<EOL><INDENT>_apps = apps<EOL><DEDENT>else:<EOL><INDENT>_apps = None<EOL><DEDENT>tables = get_tables(global_options.apps_dir, _apps, tables=options.tables,<EOL>engine_name=options.engine,<EOL>settings_file=global_options.settings,<EOL>local_settings_file=global_options.local_settings)<EOL>if options.format=='<STR_LIT>' or not options.format:<EOL><INDENT>result = generate_dot(tables, apps, engine_name=options.engine, fontname=options.font)<EOL>if options.outputfile:<EOL><INDENT>with open(options.outputfile, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(result)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print(result)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = generate_file(tables, apps, options.outputfile, options.format,<EOL>engine_name=options.engine, fontname=options.font)<EOL>if result:<EOL><INDENT>print(result)<EOL><DEDENT><DEDENT>
For Chinese Font name: 新細明體:PMingLiU 細明體:MingLiU 標楷體:DFKai-SB 黑体:SimHei 宋体:SimSun 新宋体:NSimSun 仿宋:FangSong 楷体:KaiTi 仿宋_GB2312:FangSong_GB2312 楷体_GB2312:KaiTi_GB2312 微軟正黑體:Microsoft JhengHei 微软雅黑体:Microsoft YaHei
f5738:c14:m0
def run_migrations_offline():
url = config.get_main_option("<STR_LIT>")<EOL>context.configure(url=url)<EOL>with context.begin_transaction():<EOL><INDENT>context.run_migrations()<EOL><DEDENT>
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
f5739:m0
def run_migrations_online():
from uliweb.manage import make_simple_application<EOL>from uliweb import orm, settings<EOL><INDENT>engine = engine_from_config(<EOL>config.get_section(config.config_ini_section), <EOL>prefix='<STR_LIT>', <EOL>poolclass=pool.NullPool)<EOL><DEDENT>name = config.get_main_option("<STR_LIT>")<EOL>make_simple_application(project_dir='<STR_LIT:.>')<EOL>target_metadata = orm.get_metadata(name)<EOL>connection = orm.get_connection(name).connect()<EOL><INDENT>connection = engine.connect()<EOL><DEDENT>context.configure(<EOL>connection=connection, <EOL>target_metadata=target_metadata,<EOL>compare_server_default=True,<EOL>include_object=uliweb_include_object,<EOL>compare_server_default=uliweb_compare_server_default,<EOL>)<EOL>try:<EOL><INDENT>with context.begin_transaction():<EOL><INDENT>context.run_migrations()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>connection.close()<EOL><DEDENT>
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
f5739:m3
def get_form(formcls):
from uliweb.form import Form<EOL>import inspect<EOL>if inspect.isclass(formcls) and issubclass(formcls, Form):<EOL><INDENT>return formcls<EOL><DEDENT>elif isinstance(formcls, (str, unicode)):<EOL><INDENT>path = settings.FORMS.get(formcls)<EOL>if path:<EOL><INDENT>_cls = import_attr(path)<EOL>return _cls<EOL><DEDENT>else:<EOL><INDENT>raise UliwebError("<STR_LIT>" % formcls)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise UliwebError("<STR_LIT>" % formcls)<EOL><DEDENT>
get form class according form class path or form class object
f5745:m0
def get_filename(self, filename, filesystem=False, convert=False, subpath='<STR_LIT>'):
from uliweb.utils.common import safe_unicode<EOL>s = settings.GLOBAL<EOL>if convert:<EOL><INDENT>_p, _f = os.path.split(filename)<EOL>_filename = os.path.join(_p, self.filename_convert(_f))<EOL><DEDENT>else:<EOL><INDENT>_filename = filename<EOL><DEDENT>nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING)<EOL>if subpath:<EOL><INDENT>paths = [application_path(self.to_path), subpath, nfile]<EOL><DEDENT>else:<EOL><INDENT>paths = [application_path(self.to_path), nfile]<EOL><DEDENT>f = os.path.normpath(os.path.join(*paths)).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL>if filesystem:<EOL><INDENT>return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING)<EOL><DEDENT>return f<EOL>
Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path
f5746:c3:m2
def download(self, filename, action='<STR_LIT>', x_filename='<STR_LIT>', x_sendfile=None, real_filename='<STR_LIT>'):
from uliweb import request<EOL>from uliweb.utils.common import safe_str<EOL>from uliweb.utils.filedown import filedown<EOL>s = settings.GLOBAL<EOL>action = request.GET.get('<STR_LIT:action>', action)<EOL>if not real_filename:<EOL><INDENT>real_filename = self.get_filename(filename, True, convert=False)<EOL><DEDENT>else:<EOL><INDENT>real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING)<EOL><DEDENT>if not x_filename:<EOL><INDENT>x_filename = safe_str(filename, s.FILESYSTEM_ENCODING)<EOL><DEDENT>if self.x_file_prefix:<EOL><INDENT>x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL><DEDENT>xsend_flag = bool(self.x_sendfile) if x_sendfile is None else x_sendfile<EOL>return filedown(request.environ, filename, action=action, <EOL>x_sendfile=xsend_flag, x_header_name=self.x_header_name, <EOL>x_filename=x_filename, real_filename=real_filename)<EOL>
action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it.
f5746:c3:m3
def get_url(self, filename, query_para=None, **url_args):
from uliweb.core.html import Tag<EOL>title = url_args.pop('<STR_LIT:title>', filename)<EOL>text = url_args.pop('<STR_LIT:text>', title)<EOL>query_para = query_para or {}<EOL>return str(Tag('<STR_LIT:a>', title, href=self.get_href(filename, **query_para), **url_args))<EOL>
Return <a href="filename" title="filename"> tag You should pass title and text to url_args, if not pass, then using filename
f5746:c3:m9
def find_model(sender, model_name):
MC = get_mc()<EOL>model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!='<STR_LIT>'))<EOL>if model:<EOL><INDENT>model_inst = model.get_instance()<EOL>orm.set_model(model_name, model_inst.table_name, appname=__name__, model_path='<STR_LIT>')<EOL>return orm.__models__.get(model_name)<EOL><DEDENT>
Register new model to ORM
f5749:m1
def get_model(sender, model_name, model_inst, model_info, model_config):
MC = get_mc()<EOL>if MC:<EOL><INDENT>model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!='<STR_LIT>'))<EOL>if model:<EOL><INDENT>cached_inst = __cache__.get(model_name)<EOL>if not cached_inst or (cached_inst and cached_inst[<NUM_LIT:1>]!=model.uuid):<EOL><INDENT>model_inst = model.get_instance()<EOL>M = orm.create_model(model_name, fields=eval(model_inst.fields or '<STR_LIT>'),<EOL>indexes=eval(model_inst.indexes or '<STR_LIT>'),<EOL>basemodel=model_inst.basemodel,<EOL>__replace__=True)<EOL>__cache__[model_name] = (M, model.uuid)<EOL>if model_inst.has_extension:<EOL><INDENT>ext_model_name = model_name + '<STR_LIT>'<EOL>fields = eval(model_inst.extension_fields or '<STR_LIT>')<EOL>fields.insert(<NUM_LIT:0>, {'<STR_LIT:name>':'<STR_LIT>', '<STR_LIT:type>':'<STR_LIT>', '<STR_LIT>':model_name, '<STR_LIT>':'<STR_LIT>'})<EOL>ME = orm.create_model(ext_model_name, fields=fields,<EOL>indexes=eval(model_inst.extension_indexes or '<STR_LIT>'),<EOL>basemodel=model_inst.extension_model,<EOL>__replace__=True)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>M = cached_inst[<NUM_LIT:0>]<EOL><DEDENT>return M<EOL><DEDENT><DEDENT>
#todo Add objcache support
f5749:m3
def get_model_fields(model, add_reserver_flag=True):
import uliweb.orm as orm<EOL>fields = []<EOL>m = {'<STR_LIT:type>':'<STR_LIT>', '<STR_LIT>':'<STR_LIT>',<EOL>'<STR_LIT:default>':'<STR_LIT:default>', '<STR_LIT>':'<STR_LIT>'}<EOL>m1 = {'<STR_LIT:index>':'<STR_LIT:index>', '<STR_LIT>':'<STR_LIT>'}<EOL>for name, prop in model.properties.items():<EOL><INDENT>if name == '<STR_LIT:id>':<EOL><INDENT>continue<EOL><DEDENT>d = {}<EOL>for k, v in m.items():<EOL><INDENT>d[k] = getattr(prop, v)<EOL><DEDENT>for k, v in m1.items():<EOL><INDENT>d[k] = bool(prop.kwargs.get(v))<EOL><DEDENT>d['<STR_LIT:name>'] = prop.fieldname or name<EOL>d['<STR_LIT>'] = unicode(prop.verbose_name)<EOL>d['<STR_LIT>'] = bool(prop.kwargs.get('<STR_LIT>', orm.__nullable__))<EOL>if d['<STR_LIT:type>'] in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>d['<STR_LIT:max_length>'] = prop.max_length<EOL><DEDENT>if d['<STR_LIT:type>'] in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>d['<STR_LIT>'] = prop.reference_class<EOL>d['<STR_LIT>'] = prop._collection_name<EOL><DEDENT>d['<STR_LIT>'] = prop.kwargs.get('<STR_LIT>')<EOL>d['<STR_LIT>'] = True<EOL>fields.append(d)<EOL><DEDENT>return fields<EOL>
Creating fields suit for model_config , id will be skipped.
f5749:m4
def get_model_indexes(model, add_reserver_flag=True):
import uliweb.orm as orm<EOL>from sqlalchemy.engine.reflection import Inspector<EOL>indexes = []<EOL>engine = model.get_engine().engine<EOL>insp = Inspector.from_engine(engine)<EOL>for index in insp.get_indexes(model.tablename):<EOL><INDENT>d = {}<EOL>d['<STR_LIT:name>'] = index['<STR_LIT:name>']<EOL>d['<STR_LIT>'] = index['<STR_LIT>']<EOL>d['<STR_LIT>'] = index['<STR_LIT>']<EOL>if add_reserver_flag:<EOL><INDENT>d['<STR_LIT>'] = True<EOL><DEDENT>indexes.append(d)<EOL><DEDENT>return indexes<EOL>
Creating indexes suit for model_config.
f5749:m5
def process_permission_roles(perm, v):
if isinstance(v, (tuple, list)):<EOL><INDENT>roles = v<EOL><DEDENT>else:<EOL><INDENT>roles = [v]<EOL><DEDENT>for r in roles:<EOL><INDENT>if isinstance(r, (tuple, list)):<EOL><INDENT>role_name, role_props = r<EOL><DEDENT>else:<EOL><INDENT>role_name, role_props = r, '<STR_LIT>'<EOL><DEDENT>role = Role.get(Role.c.name == role_name)<EOL>if not role:<EOL><INDENT>raise Exception('<STR_LIT>' % r)<EOL><DEDENT>rel = Rel.get((Rel.c.role==role.id) & (Rel.c.permission==perm.id))<EOL>if not rel:<EOL><INDENT>rel = Rel(role=role, permission=perm, props=role_props)<EOL>msg = '<STR_LIT>' % (name, role_name)<EOL><DEDENT>else:<EOL><INDENT>rel.update(props=role_props)<EOL>msg = '<STR_LIT>' % (name, role_name)<EOL><DEDENT>flag = rel.save()<EOL>if flag:<EOL><INDENT>print(msg)<EOL><DEDENT><DEDENT>
v is roles
f5759:m0
def add_role_func(name, func):
global __role_funcs__<EOL>__role_funcs__[name] = func<EOL>
Role_func should have 'user' parameter
f5760:m5
def has_role(user, *roles, **kwargs):
Role = get_model('<STR_LIT>')<EOL>if isinstance(user, str):<EOL><INDENT>User = get_model('<STR_LIT:user>')<EOL>user = User.get(User.c.username==user)<EOL><DEDENT>for role in roles:<EOL><INDENT>if isinstance(role, str):<EOL><INDENT>role = Role.get(Role.c.name==role)<EOL>if not role:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>name = role.name<EOL>func = __role_funcs__.get(name, None)<EOL>if func:<EOL><INDENT>if isinstance(func, str):<EOL><INDENT>func = import_attr(func)<EOL><DEDENT>assert callable(func)<EOL>para = kwargs.copy()<EOL>para['<STR_LIT:user>'] = user<EOL>flag = call_func(func, para)<EOL>if flag:<EOL><INDENT>return role<EOL><DEDENT><DEDENT>flag = role.users.has(user)<EOL>if flag:<EOL><INDENT>return role<EOL><DEDENT>flag = role.usergroups_has_user(user)<EOL>if flag:<EOL><INDENT>return role<EOL><DEDENT><DEDENT>return False<EOL>
Judge is the user belongs to the role, and if does, then return the role object if not then return False. kwargs will be passed to role_func.
f5760:m6
def has_permission(user, *permissions, **role_kwargs):
Role = get_model('<STR_LIT>')<EOL>Perm = get_model('<STR_LIT>')<EOL>if isinstance(user, str):<EOL><INDENT>User = get_model('<STR_LIT:user>')<EOL>user = User.get(User.c.username==user)<EOL><DEDENT>for name in permissions:<EOL><INDENT>perm = Perm.get(Perm.c.name==name)<EOL>if not perm:<EOL><INDENT>continue<EOL><DEDENT>flag = has_role(user, *list(perm.perm_roles.with_relation().all()), **role_kwargs)<EOL>if flag:<EOL><INDENT>return flag<EOL><DEDENT><DEDENT>return False<EOL>
Judge if an user has permission, and if it does return role object, and if it doesn't return False. role_kwargs will be passed to role functions. With role object, you can use role.relation to get Role_Perm_Rel object.
f5760:m7
def check_role(*roles, **args_map):
def f1(func, roles=roles):<EOL><INDENT>@wraps(func)<EOL>def f2(*args, **kwargs):<EOL><INDENT>from uliweb import request, error<EOL>arguments = {}<EOL>for k, v in list(args_map.items()):<EOL><INDENT>if v in kwargs:<EOL><INDENT>arguments[k] = kwargs[v]<EOL><DEDENT><DEDENT>if not has_role(request.user, *roles, **arguments):<EOL><INDENT>error(_("<STR_LIT>"))<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>return f2<EOL><DEDENT>return f1<EOL>
It's just like has_role, but it's a decorator. And it'll check request.user
f5760:m8
def check_permission(*permissions, **args_map):
def f1(func, permissions=permissions):<EOL><INDENT>@wraps(func)<EOL>def f2(*args, **kwargs):<EOL><INDENT>from uliweb import request, error<EOL>arguments = {}<EOL>for k, v in list(args_map.items()):<EOL><INDENT>if v in kwargs:<EOL><INDENT>arguments[k] = kwargs[v]<EOL><DEDENT><DEDENT>if not has_permission(request.user, *permissions, **arguments):<EOL><INDENT>error(_("<STR_LIT>"))<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>return f2<EOL><DEDENT>return f1<EOL>
It's just like has_role, but it's a decorator. And it'll check request.user
f5760:m9
def _read(self, ddfile):
import csv<EOL>d = {}<EOL>with open(ddfile) as f:<EOL><INDENT>reader = csv.DictReader(f)<EOL>for row in reader:<EOL><INDENT>key = row['<STR_LIT:name>']<EOL>if key.startswith('<STR_LIT:#>'):<EOL><INDENT>key = key[<NUM_LIT:1>:]<EOL>deprecated = True<EOL><DEDENT>else:<EOL><INDENT>deprecated = False<EOL><DEDENT>value = d.setdefault(key, {})<EOL>value[self._get_value(row)] = deprecated<EOL><DEDENT><DEDENT>return d<EOL>
Import index just like: {'key':['value', 'value'], ...}
f5762:c0:m2
def _parse_prop(self, dd, row):
key = row['<STR_LIT:name>']<EOL>if key.startswith('<STR_LIT:#>'):<EOL><INDENT>deprecated = True<EOL><DEDENT>else:<EOL><INDENT>deprecated = False<EOL><DEDENT>v = dd.get(key)<EOL>_value = self._get_value(row)<EOL>if not v:<EOL><INDENT>v = dd.setdefault(key, {})<EOL>v[_value] = deprecated<EOL><DEDENT>else:<EOL><INDENT>if not _value in v:<EOL><INDENT>v[_value] = deprecated<EOL><DEDENT><DEDENT>
:param dd: datadict :param _row: (tablename, row) :return:
f5762:c0:m4
def soap(func=None, name=None, returns=None, args=None, doc=None, target='<STR_LIT>'):
global __soap_functions__<EOL>returns = _fix_soap_kwargs(returns)<EOL>args = _fix_soap_kwargs(args)<EOL>if isinstance(func, str) and not name:<EOL><INDENT>return partial(soap, name=func, returns=returns, args=args, doc=doc, target=target)<EOL><DEDENT>if not func:<EOL><INDENT>return partial(soap, name=name, returns=returns, args=args, doc=doc, target=target)<EOL><DEDENT>target_functions = __soap_functions__.setdefault(target, {})<EOL>if inspect.isfunction(func):<EOL><INDENT>f_name = func.__name__<EOL>if name:<EOL><INDENT>f_name = name<EOL><DEDENT>target_functions[f_name] = endpoint = ('<STR_LIT:.>'.join([func.__module__, func.__name__]), returns, args, doc)<EOL>func.soap_endpoint = (f_name, endpoint)<EOL><DEDENT>elif inspect.isclass(func):<EOL><INDENT>if not name:<EOL><INDENT>name = func.__name__<EOL><DEDENT>for _name in dir(func):<EOL><INDENT>f = getattr(func, _name)<EOL>if (inspect.ismethod(f) or inspect.isfunction(f)) and not _name.startswith('<STR_LIT:_>'):<EOL><INDENT>f_name = name + '<STR_LIT:.>' + f.__name__<EOL>endpoint = ('<STR_LIT:.>'.join([func.__module__, func.__name__, _name]), returns, args, doc)<EOL>if hasattr(f, '<STR_LIT>'):<EOL><INDENT>_n, _e = f.soap_endpoint<EOL>target_functions[name + '<STR_LIT:.>' + _n] = endpoint<EOL>del target_functions[_n]<EOL><DEDENT>else:<EOL><INDENT>target_functions[f_name] = endpoint<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % func)<EOL><DEDENT>return func<EOL>
soap supports multiple SOAP function collections, it'll save functions to target dict, and you can give other target, but it should be keep up with SoapView.target definition.
f5769:m1
def _process_fields_convert_map(self, parameters, download=False):
if '<STR_LIT>' in parameters:<EOL><INDENT>_f = parameters.get('<STR_LIT>') or []<EOL>parameters['<STR_LIT>'] = self._get_fields_convert_map(_f, download)<EOL><DEDENT>
process fields_convert_map, ListView doesn't support list type but dict fields_convert_map should be define as list or dict for list, it can be: [name, name, ...] [(name, func), (name, func), ...] if func is str, it'll be the property name of class for dict, it can be: {'name':func, ...} :param model: model object :param parameters: :param prefix: it'll used to combine prefix+_convert_xxx to get convert function from class :return:
f5772:c1:m0
def _get_fields_convert_map(self, fields, download=False):
_f = fields<EOL>t = {}<EOL>def _get(name):<EOL><INDENT>_name = '<STR_LIT>'.format(name)<EOL>if download and hasattr(self, _name):<EOL><INDENT>return getattr(self, _name)<EOL><DEDENT>return getattr(self, '<STR_LIT>'.format(name))<EOL><DEDENT>if isinstance(_f, list):<EOL><INDENT>for k in _f:<EOL><INDENT>if isinstance(k, str):<EOL><INDENT>t[k] = _get(k)<EOL><DEDENT>elif isinstance(k, (tuple, list)):<EOL><INDENT>name = k[<NUM_LIT:0>]<EOL>func = k[<NUM_LIT:1>]<EOL>if isinstance(func, str):<EOL><INDENT>t[name] = _get(func)<EOL><DEDENT>elif callable(func):<EOL><INDENT>t[name] = func<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % type(func))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % type(k))<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(_f, dict):<EOL><INDENT>for k, v in _f.items():<EOL><INDENT>if isinstance(v, str):<EOL><INDENT>t[k] = _get(v)<EOL><DEDENT>elif callable(v):<EOL><INDENT>t[k] = v<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % type(func))<EOL><DEDENT><DEDENT><DEDENT>return t<EOL>
process fields_convert_map, ListView doesn't support list type but dict fields_convert_map should be define as list or dict for list, it can be: [name, name, ...] [(name, func), (name, func), ...] if func is str, it'll be the property name of class for dict, it can be: {'name':func, ...} :param model: model object :param parameters: :param prefix: it'll used to combine prefix+_convert_xxx to get convert function from class :return:
f5772:c1:m1
def _list_view(self, model, **kwargs):
from uliweb import request<EOL>fields = kwargs.pop('<STR_LIT>', None)<EOL>meta = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>if '<STR_LIT>' in request.GET:<EOL><INDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>fields = kwargs.pop('<STR_LIT>', fields)<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>meta = kwargs.pop('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if hasattr(model, '<STR_LIT>'):<EOL><INDENT>meta = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>meta = meta<EOL><DEDENT><DEDENT><DEDENT>view = functions.ListView(model, fields=fields, meta=meta, **kwargs)<EOL>return view<EOL>
:param model: :param fields_convert_map: it's different from ListView :param kwargs: :return:
f5772:c1:m2
def _query_view(self, model, **kwargs):
QueryForm = functions.get_form('<STR_LIT>')<EOL>if '<STR_LIT>' not in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = QueryForm<EOL><DEDENT>query = functions.QueryView(model, **kwargs)<EOL>return query<EOL>
:param model: :return: (query, condition) Default use QueryForm
f5772:c1:m3
def _parse_download_args(self, kwargs, fields):
downloads = {}<EOL>downloads['<STR_LIT:filename>'] = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>downloads['<STR_LIT:action>'] = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>downloads['<STR_LIT>'] = kwargs.pop('<STR_LIT>',<EOL>fields)<EOL>downloads['<STR_LIT>'] = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>downloads['<STR_LIT>'] = <NUM_LIT:0><EOL>downloads['<STR_LIT>'] = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>downloads['<STR_LIT>'] = kwargs.pop('<STR_LIT>', None)<EOL>downloads.update(kwargs.pop('<STR_LIT>', {}))<EOL>return downloads<EOL>
Parse download parameters from kwargs :return: parsed data
f5772:c1:m4
def _select_list_view(self, model, **kwargs):
from uliweb import request<EOL>fields = kwargs.pop('<STR_LIT>', None)<EOL>meta = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>if '<STR_LIT>' in request.GET:<EOL><INDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>fields = kwargs.pop('<STR_LIT>', fields)<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>meta = kwargs.pop('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if hasattr(model, '<STR_LIT>'):<EOL><INDENT>meta = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>meta = meta<EOL><DEDENT><DEDENT><DEDENT>view = functions.SelectListView(model, fields=fields, meta=meta, **kwargs)<EOL>return view<EOL>
:param model: :param fields_convert_map: it's different from ListView :param kwargs: :return:
f5772:c1:m10
def _select_list(self, model=None, queryview=None, queryform=None,<EOL>auto_condition=True,<EOL>post_view=None, post_run=None, **kwargs):
from uliweb import request, json<EOL>from uliweb.utils.generic import get_sort_field<EOL>import copy<EOL>condition = None<EOL>if queryview and auto_condition:<EOL><INDENT>queryview.run()<EOL>if hasattr(queryview, '<STR_LIT>'):<EOL><INDENT>condition = queryview.get_condition()<EOL><DEDENT><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>condition = kwargs['<STR_LIT>'] & condition<EOL><DEDENT>kwargs['<STR_LIT>'] = condition<EOL>if '<STR_LIT>' not in kwargs:<EOL><INDENT>order_by = get_sort_field(model)<EOL>if order_by is not None:<EOL><INDENT>kwargs['<STR_LIT>'] = order_by<EOL><DEDENT><DEDENT>_fields = copy.copy(kwargs.get('<STR_LIT>', []))<EOL>self._process_fields_convert_map(kwargs)<EOL>downloads = self._parse_download_args(kwargs, _fields)<EOL>self._process_fields_convert_map(downloads, download=True)<EOL>view = self._select_list_view(model, **kwargs)<EOL>if post_view:<EOL><INDENT>post_view(view)<EOL><DEDENT>if '<STR_LIT:data>' in request.values:<EOL><INDENT>return json(view.json())<EOL><DEDENT>elif '<STR_LIT>' in request.GET:<EOL><INDENT>return view.download(**downloads)<EOL><DEDENT>else:<EOL><INDENT>result = view.run()<EOL>if queryform or queryview:<EOL><INDENT>result.update({'<STR_LIT>':queryform or queryview.form})<EOL><DEDENT>else:<EOL><INDENT>result.update({'<STR_LIT>':'<STR_LIT>'})<EOL><DEDENT>result.update({'<STR_LIT>':view})<EOL>if post_run:<EOL><INDENT>post_run(view, result)<EOL><DEDENT>return result<EOL><DEDENT>
SelectListView wrap method :param auto_condition: if using queryview to create condition
f5772:c1:m11
def _search(self, model, condition=None, search_field='<STR_LIT:name>',<EOL>value_field='<STR_LIT:id>', label_field=None, pagination=True):
from uliweb import json, request<EOL>name = request.GET.get('<STR_LIT>', '<STR_LIT>')<EOL>M = functions.get_model(model)<EOL>def _v(label_field):<EOL><INDENT>if label_field:<EOL><INDENT>return lambda x: getattr(x, label_field)<EOL><DEDENT>else:<EOL><INDENT>return lambda x: unicode(x)<EOL><DEDENT><DEDENT>v_field = request.values.get('<STR_LIT:label>', '<STR_LIT:title>')<EOL>page = int(request.values.get('<STR_LIT>') or <NUM_LIT:1>)<EOL>limit = int(request.values.get('<STR_LIT>') or <NUM_LIT:10>)<EOL>v_func = _v(label_field)<EOL>if name:<EOL><INDENT>if condition is None:<EOL><INDENT>condition = M.c[search_field].like('<STR_LIT:%>' + name + '<STR_LIT:%>')<EOL><DEDENT>if pagination:<EOL><INDENT>query = M.filter(condition)<EOL>total = query.count()<EOL>rows = [{'<STR_LIT:id>': getattr(obj, value_field), v_field: v_func(obj)}<EOL>for obj in query.limit(limit).offset((page-<NUM_LIT:1>)*limit)]<EOL>result = {'<STR_LIT>':total, '<STR_LIT>':rows}<EOL><DEDENT>else:<EOL><INDENT>result = [{'<STR_LIT:id>': getattr(obj, value_field), v_field: v_func(obj)}<EOL>for obj in M.filter(condition)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = []<EOL><DEDENT>return json(result)<EOL>
Default search function :param search_field: Used for search field, default is 'name' :param value_field: Used for id field, default is id :param label_field: Used for label field, default is None, then it'll use unicode() function
f5772:c1:m12
def get_relation_condition(key):
global __relations__<EOL>return __relations__.get_condition(key)<EOL>
Get relation condition :param key: should be (schema_a, schema_b) :return:
f5774:m2
def query(d):
q = Query(d)<EOL>return q.run()<EOL>
Query schema :param d: dict options :return:
f5774:m4
def __eq__(self, key):
return key in self.relation_key<EOL>
:param key: (schema_a, schema_b) :return:
f5774:c6:m3
def add(self, relation):
r = Relation(relation)<EOL>key = r.relation_key[<NUM_LIT:0>]<EOL>if key not in self.relations:<EOL><INDENT>self.relations[key] = r<EOL>self.relations[r.relation_key[<NUM_LIT:1>]]= r<EOL><DEDENT>
relation is a string list, just like: ['User.id = Group.user', 'User.username = Group.username'] :param relation: :return:
f5774:c7:m1
def get_condition(self, relation):
condition = None<EOL>r = self.relations.get(relation)<EOL>if r:<EOL><INDENT>condition = r.get_condition(relation)<EOL><DEDENT>return condition<EOL>
:param relation: (schema_a, schema_b) :return:
f5774:c7:m2