當前位置: 首頁>>代碼示例>>Python>>正文


Python Connection.request_put方法代碼示例

本文整理匯總了Python中restful_lib.Connection.request_put方法的典型用法代碼示例。如果您正苦於以下問題:Python Connection.request_put方法的具體用法?Python Connection.request_put怎麽用?Python Connection.request_put使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在restful_lib.Connection的用法示例。


在下文中一共展示了Connection.request_put方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: Connection

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_put [as 別名]
#!/usr/bin/python

import csv
import simplejson as json
from restful_lib import Connection
#conn = Connection("http://mc933.lab.ic.unicamp.br:8010")
conn = Connection("http://mc933.lab.ic.unicamp.br:8010/getBusesPositions")
#response = conn.request_get("/getPosition")
response = conn.request_get("")

buses = json.loads(response["body"])

for i in buses:
    response = conn.request_get(str(i))
    obj = json.loads(response["body"])
    writer = csv.writer(open('points.csv', 'ab')) #, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL
    #writer.writerow(['Horario', 'Latitude', 'Longitude'])
    writer.writerow([datetime.strftime(datetime.now(), "%d/%m/%Y %H:%M:%S"), str(lat), str(lon)])
    return "Point (" + str(lat) + ',' + str(lon) + ") saved at " + datetime.strftime(datetime.now(), "%d/%m/%Y %H:%M:%S")
    #print response["body"] + "\n"
#coordenada = json.loads(response["body"])

conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'})
開發者ID:felix-dumit,項目名稱:MC933,代碼行數:25,代碼來源:rest-client.py

示例2: len

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_put [as 別名]
if len(sys.argv) != 3:
    print "You must provide a URL and JSON object"
    sys.exit(1)
    
url_re = re.compile(
    r'^https?://' # http:// or https://
    r'(?:(?:[A-Z0-9-]+\.)+[A-Z]{2,6}|' #domain...
    r'localhost|' #localhost...
    r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
    r'(?::\d+)?' # optional port
    r'(?:/?|/\S+)$', re.IGNORECASE)

# check we have a valid url
if not url_re.match(sys.argv[1]):
    print "You must provide a valid URL"
    sys.exit(1)

# print a message as it may take time for the responce to return
print "Connecting to %s" % sys.argv[1]

# make the request
try:
    conn = Connection(sys.argv[1])
    # otherwise we should just print the response
    response = conn.request_put("/", body=sys.argv[2])
except socket.error:
    print "We couldn't connect to %s" % sys.argv[1]
    sys.exit(1)

print "Response was %s" % response['headers'].status
開發者ID:garethr,項目名稱:appengine-uptime,代碼行數:32,代碼來源:put.py

示例3: RedmineRESTAPIWrapper

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_put [as 別名]
class RedmineRESTAPIWrapper(object):

    def __init__(self, settings):
        self.api_key = settings.redmine_api_key
        self.conn = Connection(settings.redmine_url)
    
    def request_put(self, path, payload):
        return self.conn.request_put(path, args= [ ('key', self.api_key) ], body=json.dumps(payload), headers={'content-type':'application/json', 'accept':'application/json'})

    def request_post(self, path, payload):
        return self.conn.request_post(path, args= [ ('key', self.api_key) ], body=json.dumps(payload), headers={'content-type':'application/json', 'accept':'application/json'})

    def request_get(self, path, payload):
        return self.conn.request_get(path, args= [ ('key', self.api_key) ] + payload, headers={'content-type':'application/json', 'accept':'application/json'})

    def put_items_with_payload(self, url, payload_name, items, payload):
        if not isinstance(items, set):
            items = set([items])
        for i in items:
            resp = self.request_put("/{}/".format(url)+str(i)+".json", { payload_name: payload})
            status = resp[u'headers']['status']
            print 'Item {} '.format(url), i, ', http status code: ', status
            if int(status) != 200:
                print resp

    def put_issues_with_payload(self, issues, payload):
        return self.put_items_with_payload("issues", "issue", issues, payload)

    def put_versions_with_payload(self, versions, payload):
        return self.put_items_with_payload("versions", "version", versions, payload)

    def post_time_entries_with_payload(self, payload):
        resp = self.request_post("/time_entries.json", {'time_entry': payload})
        status = resp[u'headers']['status']
        print 'Issue ', payload['issue_id'], ', http status code: ', status

    def get_items_as_json(self, endpoint, payload):
	resp = self.request_get("/"+endpoint+".json", payload)
        status = resp[u'headers']['status']
        return resp[u'body']

    def get_time_entries(self, payload):
        return self.get_items_as_json('time_entries', payload)

    def get_projects(self, payload):
        return self.get_items_as_json('projects', payload)

    def set_projects_parent(self, projects, parent_id):
        return self.put_items_with_payload("projects", "project", projects, { 'parent_id': parent_id})

    def add_issues_to_milestone(self, issues, version_id, milestone_name):
        self.put_issues_with_payload(issues, {'notes': 'Issue added to milestone: '+milestone_name, 'fixed_version_id': version_id})

    def add_issues_on_sprint(self, issues, sprint_id, sprint_name):
        self.put_issues_with_payload(issues, {'notes': 'Issue added to sprint "'+sprint_name+'" from REST API', 'easy_sprint_id': sprint_id})
                                         
    def set_issues_status(self, issues, status_id):
        self.put_issues_with_payload(issues, {'status_id': status_id})

    def set_issues_status_and_assigned(self, issues, status_id, assigned_id):
        self.put_issues_with_payload(issues, {'status_id': status_id, 'assigned_to_id': assigned_id})

    def set_issues_assigned(self, issues, assigned_id):
        self.put_issues_with_payload(issues, {'assigned_to_id': assigned_id})

    def set_parent_issue(self, issues, parent_id):
        self.put_issues_with_payload(issues,{'parent_issue_id': parent_id})

    def add_notes_on_issues(self, issues, notes):
        self.put_issues_with_payload(issues,{'notes': notes})

    def add_update_on_commit(self, issue, repo_name, branch_name, commit_hash, commit_msg):
        notes = "Repo <b>%s</b> branch <b>%s</b> commit <b>%s</b>: %s" % (repo_name, branch_name, commit_hash, commit_msg)
        return self.add_notes_on_issues(set([issue]), notes)

    def add_update_on_commit_from_line(self, line, repo_name, branch_name):
        (commit_hash, commit_msg) =line.split(' ',1)
        match = re.search("\#(\d+)", commit_msg)
        if match:
            issue = match.group(1)
            resp =self.add_update_on_commit(issue,repo_name, branch_name, commit_hash, commit_msg)

    def add_issues_to_milestone_1(self, issues):
        self.add_issues_to_milestone(issues, 61, "Milestone 1")

    def close_issues(self, issues):
        self.set_issues_status(issues, settings.statuses['closed'])

    def get_items_as_json_full(self, endpoint, params = None, process_cb = None):
        (offset, limit, read, total) = (0, 25, 0, 65535)
        if params is None: params = []
        result = []
        while read<total:
            _params = params + [('limit', limit), ('offset', offset)]
            resp = json.loads(self.get_items_as_json(endpoint, _params))
#            add_to_list(resp["time_entries"], label)
            result += resp[endpoint]
            if process_cb is not None:
                process_cb(resp[endpoint])

#.........這裏部分代碼省略.........
開發者ID:62mkv,項目名稱:py-redmine-helper,代碼行數:103,代碼來源:redmine_rest_wrapper.py

示例4: __init__

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_put [as 別名]
class SensorBase:

    def __init__(self, host, email, password):
        """
        Set up a connection with the sensorbase host
        """
        
        self.host = host
        self.email = email
        self.password = password

        self.connection = Connection(self.host, self.email, self.password)

    def get_sensordata(self,user=None):
        """
        Deprecated! Written during development to get acquainted with
        Hackystat's REST API. Might become handy if sensorbase.py becomes
        a python lib to interact with hackystat. Refactoring needed?
        """
        
        if user == None:
            user = self.email

        response = self.connection.request_get("/sensordata"+user)
        xml_string = response[u'body']
        
        tree = ET.XML(xml_string)
        ET.dump(tree)

    def put_sensordata(self, datatype="", tool="", resource="", properties=""):
        """
        Used to put up new sensordata on the hackystat server. Creates and
        XML element tree according to the xml schema (hardcoded). Will probably
        need some refactoring later on.
        """

        time = self.get_timestamp()

        # build a tree structure
        e_sensordata = ET.Element("SensorData")

        e_timestamp = ET.SubElement(e_sensordata, "Timestamp")
        e_timestamp.text = time
        
        e_runtime = ET.SubElement(e_sensordata, "Runtime")
        e_runtime.text = time

        e_tool = ET.SubElement(e_sensordata, "Tool")
        e_tool.text = tool

        e_datatype = ET.SubElement(e_sensordata, "SensorDataType")
        e_datatype.text = datatype

        e_resource = ET.SubElement(e_sensordata, "Resource")
        e_resource.text = resource

        e_owner = ET.SubElement(e_sensordata, "Owner")
        e_owner.text = self.email

        e_properties = ET.SubElement(e_sensordata, "Properties")

        for property_key in properties.keys():
            e_property = ET.SubElement(e_properties, "Property")
            e_key = ET.SubElement(e_property, "Key")
            e_key.text = property_key
            e_value = ET.SubElement(e_property, "Value")
            e_value.text = properties[property_key]

        uri = "/sensordata/[email protected]/"+time
        response = self.connection.request_put(uri, None,
                                               ET.tostring(e_sensordata))
        print response
        

    def get_timestamp(self,hour=0,minute=0):
        time_current = datetime.now()
        time_current = time_current + timedelta(hours=hour,minutes=minute)

        #Time format for both oldcurrent timestamp
        time_format = "%Y-%m-%dT%H:%M:%S.000"
        timestamp = time.strftime(time_format, time_current.timetuple())

        return timestamp

    def get_sensor_datatype(self,data):
        """
        Deprecated! Written during development to get acquainted with
        Hackystat's REST API. Might become handy if sensorbase.py becomes
        a python lib to interact with hackystat. Refactoring needed?
        """
        
        name = data.attrib['Name']
        response = self.connection.request_get("/sensordatatypes/"+name)

        xml_string = response[u'body']

        tree = ET.XML(xml_string)
        return response[u'body']

    def get_projectdata(self,user=None,project=None,args=None):
#.........這裏部分代碼省略.........
開發者ID:hackystat,項目名稱:hackystat-sensorbase-uh,代碼行數:103,代碼來源:sensorbase.py

示例5: __init__

# 需要導入模塊: from restful_lib import Connection [as 別名]
# 或者: from restful_lib.Connection import request_put [as 別名]
class Odl:
    """Connect to ODL and do REST transactions."""
    def __init__(self, base_url):
        """Connect to ODL."""
        self.conn = Connection(base_url, username=v.username,
                      password=v.password)
        self.log = logging.getLogger('ODL')

    def clean_up(self):
        """Clean up ODL configuration."""
        params = {'node_id': v.rt1_node_id,
                  'name': v.auto_tunnel_name}
        self.post_remove_lsp(params)

    def read_file(self, filename, params=None):
        """Return the file contents after substituting the params if any."""
        f = open(filename, 'r')
        contents = f.read()
        f.close()
        if params:
            contents = Template(contents)
            contents = contents.substitute(params)

        return contents

    def get(self, path):
        """Request REST GET transaction with timeout."""
        return timeout(self, self.request, ('GET', path, {}))

    def post(self, path, body):
        """Request REST POST transaction with timeout."""
        return timeout(self, self.request, ('POST', path, body))

    def put(self, path, body):
        """Request REST PUT transaction with timeout."""
        return timeout(self, self.request, ('PUT', path, body))

    def request(self, operation, path, body):
        """Request REST transactions."""
        self.log.info("%s : %s", operation, path)

        if body != {}:
            self.log.debug("Body : %s", json.dumps(json.loads(body), indent=2))

        headers = {'content-type':'application/json', 'accept':'application/json'}

        if operation == 'GET':
            response = self.conn.request_get(path, args={}, headers=headers)
        elif operation == 'POST':
            response = self.conn.request_post(path, args={}, body=body, headers=headers)
        elif operation == 'PUT':
            response = self.conn.request_put(path, args={}, body=body, headers=headers)

        status = int(response['headers']['status'])

        self.log.info("Response : %s %s", status, httplib.responses[status])

        response_body = json.loads(response['body'])
        self.log.debug("Response Body : %s\n", json.dumps(response_body, indent=2))

        return status, response_body

    def get_pcep_topology(self, params=None):
        """Return the content of PCEP topology response."""
        return self.get("/operational/network-topology:network-topology/topology/pcep-topology")

    def post_add_lsp(self, params=None):
        """Add LSP and return the content of the response."""
        self.node_id = params['node_id']  # Required for auto undo
        if params.has_key('sid'):
            body = self.read_file(v.add_lsp_sr_file, params)
        elif params.has_key('sid2'):
            body = self.read_file(v.add_lsp_sr2_file, params)
        elif params.has_key('sid3'):
            body = self.read_file(v.add_lsp_sr3_file, params)
        else:
            body = self.read_file(v.add_lsp_file, params)
        return self.post("/operations/network-topology-pcep:add-lsp", body)

    def post_update_lsp(self, params=None):
        """Update LSP and return the content of the response."""
        if params.has_key('sid'):
            body = self.read_file(v.update_lsp_sr_file, params)
        elif params.has_key('sid2'):
            body = self.read_file(v.update_lsp_sr2_file, params)
        elif params.has_key('sid3'):
            body = self.read_file(v.update_lsp_sr3_file, params)
        else:
            body = self.read_file(v.update_lsp_file, params)
        return self.post("/operations/network-topology-pcep:update-lsp", body)

    def post_remove_lsp(self, params=None):
        """Remove LSP and return the content of the response."""
        if params is None:
            # Auto undo
            params = {}
            move_attr_to_params(self, params, 'node_id')

        if params.has_key("node_id"):
            body = self.read_file(v.remove_lsp_file, params)
#.........這裏部分代碼省略.........
開發者ID:SojanKoshy,項目名稱:bgpcep-pcecc,代碼行數:103,代碼來源:odl.py


注:本文中的restful_lib.Connection.request_put方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。