Best Python code snippet using rester_python
plantuml.py
Source:plantuml.py  
1#!/usr/bin/env python2"""3https://github.com/dougn/python-plantuml/4requirements.txt5sphinx6httplib27twine8wheel9"""10from __future__ import print_function11import base6412import string13from argparse import ArgumentParser14from io import open15from os import environ, path, makedirs16from zlib import compress17import httplib218import six19from six.moves.urllib.parse import urlencode20if six.PY2:21    from string import maketrans22else:23    maketrans = bytes.maketrans24__version__ = 0, 3, 025__version_string__ = '.'.join(str(x) for x in __version__)26__author__ = 'Doug Napoleone, Samuel Marks, Eric Frederich'27__email__ = 'doug.napoleone+plantuml@gmail.com'28plantuml_alphabet = string.digits + string.ascii_uppercase + string.ascii_lowercase + '-_'29base64_alphabet   = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'30b64_to_plantuml = maketrans(base64_alphabet.encode('utf-8'), plantuml_alphabet.encode('utf-8'))31class PlantUMLError(Exception):32    """33    Error in processing.34    """35    pass36class PlantUMLConnectionError(PlantUMLError):37    """38    Error connecting or talking to PlantUML Server.39    """40    pass41class PlantUMLHTTPError(PlantUMLConnectionError):42    """43    Request to PlantUML server returned HTTP Error.44    """45    def __init__(self, response, content, *args, **kwdargs):46        self.response = response47        self.content = content48        message = "%d: %s" % (self.response.status, self.response.reason)49        if not getattr(self, 'message', None):50            self.message = message51        super(PlantUMLHTTPError, self).__init__(message, *args, **kwdargs)52def deflate_and_encode(plantuml_text):53    """zlib compress the plantuml text and encode it for the plantuml server.54    """55    zlibbed_str = compress(plantuml_text.encode('utf-8'))56    compressed_string = zlibbed_str[2:-4]57    return base64.b64encode(compressed_string).translate(b64_to_plantuml).decode('utf-8')58class PlantUML(object):59    """Connection to a PlantUML server with optional authentication.60    61    All parameters are optional.62    63    :param str url: URL to the PlantUML server image CGI. defaults to64                    http://www.plantuml.com/plantuml/img/65    :param dict basic_auth: This is if the plantuml server requires basic HTTP66                    authentication. Dictionary containing two keys, 'username'67                    and 'password', set to appropriate values for basic HTTP68                    authentication.69    :param dict form_auth: This is for plantuml server requires a cookie based70                    webform login authentication. Dictionary containing two71                    primary keys, 'url' and 'body'. The 'url' should point to72                    the login URL for the server, and the 'body' should be a73                    dictionary set to the form elements required for login.74                    The key 'method' will default to 'POST'. The key 'headers'75                    defaults to76                    {'Content-type':'application/x-www-form-urlencoded'}.77                    Example: form_auth={'url': 'http://example.com/login/',78                    'body': { 'username': 'me', 'password': 'secret'}79    :param dict http_opts: Extra options to be passed off to the80                    httplib2.Http() constructor.81    :param dict request_opts: Extra options to be passed off to the82                    httplib2.Http().request() call.83                    84    """85    def __init__(self, url, basic_auth={}, form_auth={},86                 http_opts={}, request_opts={}):87        self.HttpLib2Error = httplib2.HttpLib2Error88        self.url = url89        self.request_opts = request_opts90        self.auth_type = 'basic_auth' if basic_auth else (91            'form_auth' if form_auth else None)92        self.auth = basic_auth if basic_auth else (93            form_auth if form_auth else None)94        # Proxify95        try:96            from urlparse import urlparse97            import socks98            proxy_uri = urlparse(environ.get('HTTPS_PROXY', environ.get('HTTP_PROXY')))99            if proxy_uri:100                proxy = {'proxy_info': httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP,101                                                          proxy_uri.hostname, proxy_uri.port)}102                http_opts.update(proxy)103                self.request_opts.update(proxy)104        except ImportError:105            pass106        self.http = httplib2.Http(**http_opts)107        if self.auth_type == 'basic_auth':108            self.http.add_credentials(109                self.auth['username'], self.auth['password'])110        elif self.auth_type == 'form_auth':111            if 'url' not in self.auth:112                raise PlantUMLError(113                    "The form_auth option 'url' must be provided and point to "114                    "the login url.")115            if 'body' not in self.auth:116                raise PlantUMLError(117                    "The form_auth option 'body' must be provided and include "118                    "a dictionary with the form elements required to log in. "119                    "Example: form_auth={'url': 'http://example.com/login/', "120                    "'body': { 'username': 'me', 'password': 'secret'}")121            login_url = self.auth['url']122            body = self.auth['body']123            method = self.auth.get('method', 'POST')124            headers = self.auth.get(125                'headers', {'Content-type': 'application/x-www-form-urlencoded'})126            try:127                response, content = self.http.request(128                    login_url, method, headers=headers,129                    body=urlencode(body))130            except self.HttpLib2Error as e:131                raise PlantUMLConnectionError(e)132            if response.status != 200:133                raise PlantUMLHTTPError(response, content)134            self.request_opts['Cookie'] = response['set-cookie']135    def get_url(self, plantuml_text):136        """Return the server URL for the image.137        You can use this URL in an IMG HTML tag.138        139        :param str plantuml_text: The plantuml markup to render140        :returns: the plantuml server image URL141        """142        return self.url + deflate_and_encode(plantuml_text)143    def processes(self, plantuml_text):144        """Processes the plantuml text into the raw PNG image data.145        146        :param str plantuml_text: The plantuml markup to render147        :returns: the raw image data148        """149        url = self.get_url(plantuml_text)150        try:151            response, content = self.http.request(url, **self.request_opts)152        except self.HttpLib2Error as e:153            raise PlantUMLConnectionError(e)154        if response.status != 200:155            raise PlantUMLHTTPError(response, content)156        return content157    def processes_file(self, filename, outfile=None, errorfile=None, directory=''):158        """Take a filename of a file containing plantuml text and processes159        it into a .png image.160        161        :param str filename: Text file containing plantuml markup162        :param str outfile: Filename to write the output image to. If not163                    supplied, then it will be the input filename with the164                    file extension replaced with '.png'.165        :param str errorfile: Filename to write server html error page166                    to. If this is not supplined, then it will be the167                    input ``filename`` with the extension replaced with168                    '_error.html'.169        :returns: ``True`` if the image write succedded, ``False`` if there was170                    an error written to ``errorfile``.171        """172        if outfile is None:173            outfile = path.splitext(filename)[0] + '.png'174        if errorfile is None:175            errorfile = path.splitext(filename)[0] + '_error.html'176        if directory and not path.exists(directory):177            makedirs(directory)178        data = open(filename).read()179        try:180            content = self.processes(data)181        except PlantUMLHTTPError as e:182            err = open(path.join(directory, errorfile), 'w')183            err.write(e.content)184            err.close()185            return False186        out = open(path.join(directory, outfile), 'wb')187        out.write(content)188        out.close()189        return True190def _build_parser():191    parser = ArgumentParser(description='Generate images from plantuml defined files using plantuml server')192    parser.add_argument('files', metavar='filename', nargs='+',193                        help='file(s) to generate images from')194    parser.add_argument('-o', '--out', default='',195                        help='directory to put the files into')196    parser.add_argument('-s', '--server', default='http://www.plantuml.com/plantuml/img/',197                        help='server to generate from, defaults to "http://www.plantuml.com/plantuml/img/"')198    return parser199def main():200    args = _build_parser().parse_args()201    pl = PlantUML(args.server)202    print(list(map(lambda filename: {'filename': filename,203                                'gen_success': pl.processes_file(filename, directory=args.out)}, args.files)))204if __name__ == '__main__':...menu.py
Source:menu.py  
1from argparse import ArgumentParser2parser = ArgumentParser(add_help=False)3parser.add_argument('--help',    '-h',  help='show this help message and exit', action='store_true'           )4parser.add_argument('--proxy',   '-p',  help='proxy [IP:PORT]'                                                )5parser.add_argument('--log',     '-l',  help='enable logging',    action='store_true'                         )6parser.add_argument('--ssl',     '-s',  help='enable ssl',        action='store_true'                         )7parser.add_argument('--threads', '-t',  help='thread(s) number [default=1]', type=int                         )8request_opts = parser.add_argument_group('[Requests Options]'                                                 )9request_opts.add_argument('--request',      '-r',  help='request file',                                       )10request_opts.add_argument('--delay',        '-d',  help="set a delay between requests [default=0.05]"         )11request_opts.add_argument('--encode',       '-e',  help="encode space chars in uri/body",  action='store_true')12request_opts.add_argument('--full-encode',  '-fe', help="encode all chars in uri/body"  ,  action='store_true')13output_opts = parser.add_argument_group('[Output Options]'                                                    )14output_opts.add_argument('--output',         '-o' , help='output type [terminal/folder name]'                 )15output_opts.add_argument('--output-details', '-od', help='outputting more details [terminal/folder name]'     )16modules = parser.add_argument_group('[Modules]'                                                               )17modules.add_argument('--fuzz',        '-f',  help="run fuzzing module", action='store_true'                   )18modules.add_argument('--charfuzz',    '-cf', help="run char fuzzing module", action='store_true'              )19modules.add_argument('--manipulate',  '-m',  help="run manipulating headers module", action='store_true'      )20parser.add_argument('--version', '-v', action='version',  version='pFuzz Advanced Fuzzing Tool v0.2.4\n\21                                                                 @EmreOvunc\n\22                                                                 @merttasci\n\23                                                                 @xsuperbug'                                  )24parser.epilog = "Usage: python3 pfuzz.py -r req.txt -l -s -p 127.0.0.1:8080 --fuzz -e --delay 0.5 -o terminal"...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
