working on it ...

Filters

Explore Public Snippets

Sort by

Found 85k snippets matching: python

    public by vietkute02 modified Dec 29, 2013  1544176  273  5  2

    convert suds response to dictionary

    from suds.sudsobject import asdict
    
    def recursive_asdict(d):
        """Convert Suds object into serializable format."""
        out = {}
        for k, v in asdict(d).iteritems():
            if hasattr(v, '__keylist__'):
                out[k] = recursive_asdict(v)
            elif isinstance(v, list):
                out[k] = []
                for item in v:
                    if hasattr(item, '__keylist__'):
                        out[k].append(recursive_asdict(item))
                    else:
                        out[k].append(item)
            else:
                out[k] = v
        return out
    
    def suds_to_json(data):
        return json.dumps(recursive_asdict(data))

    public by lbottaro modified Mar 18, 2014  1191746  42  7  0

    Using lambda function to pass extra argument to slots using PyQt4 python

    When programming with PyQt is useful to pass extra arguments to slots callback methods, in order to execute some code when a UI control's action is invoked. In this example you can see the usage of lambda expression to pass the extra argument to the method invoked when pressing a button. Thanks to http://eli.thegreenplace.net/2011/04/25/passi
    self.greeting = QLabel('', self)
    
    # Create the build button with its caption
    self.build_button = QPushButton('&Build Greeting', self)
     
    # Connect the button's clicked signal to AddControl
    self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
    
    def AddControl(self, name):
        self.greeting.setText('%s!' % (name))
    
    

    public by marksimon232 modified Aug 8, 2014  1002187  29  5  3

    How to add Cookies and Headers in HTTP requests in Python

    Let's say I have an HTTP GET request and I want to decorate it with some Headers (e.g. "Accept" or "Authorization") and with some Cookies. What's the best way to do this in Python?
    => According to the api - http://docs.python-requests.org/en/latest/api/, the headers can all be passed in using requests.get:
    r=requests.get("http://www.example.com/", headers={"content-type":"text"});
    
    
    => Response Headers:
    We can view the server’s response headers using a Python dictionary:
    >>> r.headers
    {
        'status': '200 OK',
        'content-encoding': 'gzip',
        'transfer-encoding': 'chunked',
        'connection': 'close',
        'server': 'nginx/1.0.4',
        'x-runtime': '148ms',
        'etag': '"e1ca502697e5c9317743dc078f67693f"',
        'content-type': 'application/json; charset=utf-8'
    }
    
    
    => HTTP Headers are case-insensitive, so we can access the headers using any
    capitalization we want.
    >>> r.headers['Content-Type']
    'application/json; charset=utf-8'
    
    >>> r.headers.get('content-type')
    'application/json; charset=utf-8'
    
    # If a header doesn’t exist in the Response, its value defaults to None:
    >>> r.headers['X-Random']
    None
    
    
    => Cookies
    If a response contains some Cookies, you can get quick access to them:
    >>> url = 'http://http.org/cookies/set/requests-is/awesome'
    >>> r = requests.get(url)
    
    >>> r.cookies['requests-is']
    'awesome'
    # To send your own cookies to the server, you can use the cookies parameter:
    
    >>> url = 'http://http.org/cookies'
    >>> cookies = dict(cookies_are='working')
    
    >>> r = requests.get(url, cookies=cookies)
    
    >>> r.text
    '{"cookies": {"cookies_are": "working"}}'
    

    public by lbottaro modified Oct 30, 2013  903618  36  7  0

    How to parse the JSON result of a jenkins job in python

    This snippet shows how to get and parse the JSON format of the last execution of a Jenkins job. You have to specify: Jenkins_server - The Jenkins server name/IP address http_port - The port used by Jenkins server job_name - The job name
    import urllib2
    import json 
    
    jenkins_job_dir="http://<Jenkins_server>:<http_port>/view/All/job/<job_name>/lastBuild/api/json"
    def getBuildResult():
        try:      
            jenkinsStream    = urllib2.urlopen(jenkins_job_dir)
    
        except urllib2.HTTPError, e:
            print "URL Error: " + str(e.code) 
            return "FAILURE"
        
        try:
            buildStatusJson = json.load( jenkinsStream )
        except:
            print "Failed to parse json"
            return "FAILURE"
    
        if buildStatusJson.has_key( "result" ):      
            print "build status job " + buildStatusJson["result"]
            if buildStatusJson["result"] != "SUCCESS" :
                return "FAILURE"
        else:
            return "FAILURE"
        return "SUCCESS"
    
    print "loading"
    getBuildResult()
    print "Done"

    public by lbottaro modified Oct 24, 2013  644673  11  7  2

    Using Pickle to Save Objects in Python - String Serialization

    You can use the pickle module to save data in a serialized format, typically in a txt string, performing what is better known as data serialization, marshalling, or flattening. Pickle allows you to save an object to a file for later retrieval. Pickling some data will write the python object (dictionary, list, tuple, class) as one long strea
    import pickle 
    
    # The data to save
    myDict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    # The object to pickle
    object_pi = myDict 
    # The file where to write the serialized string
    file_pi = open('filename_pi.obj', 'w')
    # Dump the data as string to file 
    pickle.dump(object_pi, file_pi)
    file_pi.close()

    public by lbottaro modified Oct 30, 2013  564583  12  7  2

    How to create a simple GUI in python using PyQt4

    In this example, we create a simple window using PyQt4 and its QtGui module. Thanks to http://zetcode.com/gui/pyqt4/firstprograms/
    #!/usr/bin/python
    import sys
    from PyQt4 import QtGui
    
    def main():
        # Every PyQt4 application must create an application object.
        # The application object is located in the QtGui module.
        app = QtGui.QApplication(sys.argv)
    
       # The QWidget widget is the base class of all user interface objects in PyQt4.
       # We provide the default constructor for QWidget. The default constructor has no parent.
        # A widget with no parent is called a window.
        w = QtGui.QWidget()
    
        # The resize() method resizes the widget.
        w.resize(250, 150)
        w.move(300, 300)
    
        # Here we set the title for our window.
        w.setWindowTitle('Simple')
    
        # The show() method displays the widget on the screen.
        w.show()
        
        # Finally, we enter the mainloop of the application.
        sys.exit(app.exec_())
    
    if __name__ == '__main__':
        main()

    public by lbottaro modified Oct 30, 2013  599034  19  7  0

    How to create a simple button in python using GUI PyQt4

    Using PyQt4 python module, you can easily add a QtGui.QPushButton as interactive button in your mask. Constructor QPushButton(string text, QWidget parent = None). The 'text' parameter is the text displayed on the button. The 'parent' is a widget, onto which we place the button. Thanks to http://zetcode.com/gui/pyqt4/firstprograms/
    #!/usr/bin/python
    
    import sys
    from PyQt4 import QtGui, QtCore
    
    class GUI_Example(QtGui.QWidget):
        
        def __init__(self):
            super(GUI_Example, self).__init__()
            self.initUI()
            
        def initUI(self):               
            
            qbtn = QtGui.QPushButton('Quit', self)
            qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
            qbtn.resize(qbtn.sizeHint())
            qbtn.move(55, 55)       
            
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Quit button')    
            self.show()
            
    def main():
        
        app = QtGui.QApplication(sys.argv)
        ex = GUI_Example()
        sys.exit(app.exec_())
    
    if __name__ == '__main__':
        main()
    

    public by lbottaro modified Feb 13, 2014  539358  9  7  1

    How to check if a Git remote repository is available in python

    This simple python code shows how to check if a given Git remote repository is available. The code invokes the git command 'git ls-remote' on the remote URL path as subprocess with Popen and checks the exit code, using the communicate() method. The command exit status is stored into the 'returncode' property. A value not-equals to '0' mean
    from subprocess import Popen, PIPE, STDOUT
    
    p = Popen(["git", "ls-remote", "git://remote_path"], stdout=PIPE)
    output = p.communicate()[0]
    if p.returncode != 0:
      print "Command failed ["+str(p.returncode)+"]"        

    public by fabio.nosenzo @ Amazon_AWS_Python_API modified Aug 1, 2013  586741  5  7  0

    Amazon S3 Aws - S3Connection object from python boto API

    This snippet is about the S3Connection object provided by python boto package for Amazon AWS API. Here the __init__ method is listed with all its variables. The AWSAuthConnection object is initialized and it handles all the data for managing requests and response from Amazon AWS service. Path: [boto/s3/connection.py] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', 's3.amazonaws.com')
        DefaultCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.SubdomainCallingFormat')
        QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
    
        def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                     is_secure=True, port=None, proxy=None, proxy_port=None,
                     proxy_user=None, proxy_pass=None,
                     host=DefaultHost, debug=0, https_connection_factory=None,
                     calling_format=DefaultCallingFormat, path='/',
                     provider='aws', bucket_class=Bucket, security_token=None,
                     suppress_consec_slashes=True, anon=False,
                     validate_certs=None):
            if isinstance(calling_format, str):
                calling_format=boto.utils.find_class(calling_format)()
            self.calling_format = calling_format
            self.bucket_class = bucket_class
            self.anon = anon
            AWSAuthConnection.__init__(self, host,
                    aws_access_key_id, aws_secret_access_key,
                    is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
                    debug=debug, https_connection_factory=https_connection_factory,
                    path=path, provider=provider, security_token=security_token,
                    suppress_consec_slashes=suppress_consec_slashes,
                    validate_certs=validate_certs)

    public by lbottaro @ Amazon_AWS_Python_API modified Aug 4, 2013  570477  13  7  0

    Amazon S3 Aws - How to get content information for a given bucket using boto python api

    This snippet shows how to iterate through your own Amazon S3 buckets and list the available content.
    import boto
    import boto.s3.connection
    access_key = '<aws access key>'
    secret_key = '<aws secret key>'
    
    # This code initialize the Amazon S3 connection to your account
    conn = boto.connect_s3(
            aws_access_key_id = access_key,
            aws_secret_access_key = secret_key)
    
    # Iteration through all available buckets stored into S3
    # Name and creation date are listed
    for bucket in conn.get_all_buckets():
            print "{name}\t{created}".format(
                    name = bucket.name,
                    created = bucket.creation_date,
            )
            # For each bucket get all data content put into the bucket
            for key in bucket.list():
                    # Get name, size and date
                    print "{name}\t{size}\t{modified}".format(
                            name = key.name,
                            size = key.size,
                            modified = key.last_modified,
                            )
    • Public Snippets
    • Channels Snippets