def getWeather(self, sender, event):

        zipcode = self.textbox1.Text
        country = self.combobox1.Text
        appid = "get your own appid"

        uri = "http://api.openweathermap.org/data/2.5/weather?zip=" + zipcode + "," + country + "&APPID=" + appid
        request = HttpWebRequest.Create(uri)
        response = request.GetResponse()

        # the variable response now holds a JSON string.
        # in order to parse the JSON string, response has to first be converted into a "stream" using StreamReader()
        #   so it can then be deserialized using the JavaScriptSerializer() and converted into a dictionary.
        stream_reader = StreamReader(response.GetResponseStream())
        json_object = stream_reader.ReadToEnd()
        my_data = JavaScriptSerializer().DeserializeObject(json_object)

        # get the data from the dictionary and display it
        # this api returns temperature as KELVIN so it needs to be converted to FAHRENHEIT
        city = str(my_data['name'])
        temp_kelvin = float(my_data['main']['temp'])
        temp_fahrenheit = float((temp_kelvin - 273.15) * 1.8 + 32)

        self.textbox2.Text = "The temperature in " + city + " is " + str(
            temp_fahrenheit) + " F"

        pass
def apiRequest(relativeUrl):
    url = baseUrl + relativeUrl
    print 'calling url ' + url
    request = HttpWebRequest.Create(url)
    request.Method = 'GET'
    request.Accept = 'application/json'
    request.Headers.Add('Authorization', 'Bearer ' + accessToken)
    response = request.GetResponse()
    data = json.loads(StreamReader(response.GetResponseStream()).ReadToEnd())
    return data
def request_get(uri):
    webRequest = HttpWebRequest.Create(uri)
    webRequest.Method = 'GET'
    webRequest.ContentType = 'application/json'
    webRequest.ContentLength = 0
    response = webRequest.GetResponse()
    streamReader = StreamReader(response.GetResponseStream())
    jsonData = json.loads(streamReader.ReadToEnd())
    response.Close()
    return jsonData
def uploadOneFile(dataTable):
    outputFile = StreamWriter(outputFilePath, "a")
    fileName = dataTable.Name
    outputFile.Write("<p>" + str(datetime.datetime.now()) + " - " + fileName +
                     " - start <br/>\n")

    webRequest = HttpWebRequest.Create(rcqBackendURI + fileName)
    response = webRequest.GetResponse()
    streamReader = StreamReader(response.GetResponseStream())
    jsonData = streamReader.ReadToEnd()
    ps.CurrentProgress.CheckCancel()

    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName + " " + str(jsonData) +
        "<br/>\n")

    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName +
        " - SDBF file re-generated <br/>\n")
    dataTable.Refresh()
    ps.CurrentProgress.CheckCancel()
    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName +
        " - Analysis Refreshed <br/>\n")

    try:
        (found,
         item) = lm.TryGetItem(folder + fileName, LibraryItemType.SbdfDataFile,
                               LibraryItemRetrievalOption.IncludeProperties)
        if found:
            table.ExportDataToLibrary(item, fileName)
            outputFile.Write(
                str(datetime.datetime.now()) + " - " + fileName +
                " - exported (ow) <br/>\n")
        else:
            (found2, item2) = lm.TryGetItem(
                folder, LibraryItemType.Folder,
                LibraryItemRetrievalOption.IncludeProperties)
            if found2:
                table.ExportDataToLibrary(item2, fileName)
                outputFile.Write(
                    str(datetime.datetime.now()) + " - " + fileName +
                    " - exported (1st) <br/>\n")
    except Exception as e:
        outputFile.Write(
            str(datetime.datetime.now()) + " - " + "Exception Occured:" +
            str(e) + " <br/>\n")

    outputFile.Write("</p>\n")
    outputFile.Close()
    def get_source(self, URI):
        """URI should be a valid URI instance"""

        success = True

        try:

            request = HttpWebRequest.Create(URI)
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"

        except (ArgumentNullException, System.Security.SecurityException), ex:

            self._exception = ex
            return False
Esempio n. 6
0
def read_wiki(column_size=50):
    # Create a CLR web request object
    http = HttpWebRequest.Create(url)
    http.Timeout = 5000
    http.UserAgent = "Red Gate SQL Data Generator"

    # Read the response with a CLR StreamReader
    response = http.GetResponse()
    responseStream = StreamReader(response.GetResponseStream())
    html = responseStream.ReadToEnd()

    # Yield all lines that start with a *,
    # truncated to the column width
    for line in html.splitlines():
        if line.startswith("*"):
            yield line[:column_size]
def login():
    global accessToken

    requestBody = 'grant_type=client_credentials&scope=ata-administrator+ata-technician'
    url = baseUrl + '/authenticate'
    webRequest = HttpWebRequest.Create(url)
    webRequest.Method = 'POST'
    webRequest.ContentType = 'application/x-www-form-urlencoded'
    webRequest.Headers.Add('Authorization', 'Basic ' + credentials)
    bytes = Encoding.ASCII.GetBytes(requestBody)
    webRequest.ContentLength = bytes.Length
    requestStream = webRequest.GetRequestStream()
    requestStream.Write(bytes, 0, bytes.Length)
    requestStream.Close()

    response = webRequest.GetResponse()

    jsonString = StreamReader(response.GetResponseStream()).ReadToEnd()
    data = json.loads(jsonString)
    accessToken = data['access_token']
    print 'accessToken', accessToken
    return accessToken
def upload_one_file(data_table):
    file_name = data_table.Name
    lm = Application.GetService(LibraryManager)
    ps.CurrentProgress.ExecuteSubtask(file_name + " - start")

    web_request = HttpWebRequest.Create(rcqBackendURI + file_name)
    response = web_request.GetResponse()
    stream_reader = StreamReader(response.GetResponseStream())
    json_data = stream_reader.ReadToEnd()
    ps.CurrentProgress.CheckCancel()

    ps.CurrentProgress.ExecuteSubtask(file_name + ": " + str(json_data))
    ps.CurrentProgress.ExecuteSubtask(file_name + " - SDBF file re-generated")
    data_table.Refresh()
    ps.CurrentProgress.CheckCancel()
    ps.CurrentProgress.ExecuteSubtask(file_name +
                                      " - Analysis DataTable Refreshed")

    try:
        (found,
         item) = lm.TryGetItem(folder + file_name,
                               LibraryItemType.SbdfDataFile,
                               LibraryItemRetrievalOption.IncludeProperties)
        if found:
            data_table.ExportDataToLibrary(item, file_name)
            ps.CurrentProgress.ExecuteSubtask(file_name + " - exported (ow)")
        else:
            (found2, item2) = lm.TryGetItem(
                folder, LibraryItemType.Folder,
                LibraryItemRetrievalOption.IncludeProperties)
            if found2:
                data_table.ExportDataToLibrary(item2, file_name)
                ps.CurrentProgress.ExecuteSubtask(file_name +
                                                  " - exported (1st)")
    except Exception as e:
        ps.CurrentProgress.ExecuteSubtask("Exception occurred on " +
                                          file_name + " - " + str(e))
Esempio n. 9
0
        def search(self, jql):
            clr.AddReference("System.Web")
            from System.Web import HttpUtility
            from System.Net import HttpWebRequest
            from System.IO import StreamReader
            clr.AddReference("Newtonsoft.Json")
            from Newtonsoft.Json import JsonTextReader
            from Newtonsoft.Json.Linq import JObject
            from System import Decimal
            import Newtonsoft.Json
            clr.ImportExtensions(Newtonsoft.Json.Linq)
            usernamepw = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(
                    String.Format("{0}:{1}", self.username, self.password)))

            fieldsparam = String.Join(",", self.requestedFields)
            requestUri = String.Format(
                "{0}rest/api/2/search?jql={1}&fields={2}",
                self.repository.AbsoluteUri, HttpUtility.UrlEncode(jql),
                fieldsparam)
            Logger.Write(LogLevel.Verbose, "Jira.Search: {0}", requestUri)

            request = HttpWebRequest.Create(requestUri)
            request.ContentType = "application/json"

            request.Headers.Add("Authorization", "Basic " + usernamepw)

            request.Method = "GET"
            with request.GetResponse() as response:
                with StreamReader(response.GetResponseStream()) as sr:
                    with JsonTextReader(sr) as jr:
                        result = JObject.Load(jr)
                        issues = result["issues"]

                        items = list()
                        for issue in issues:
                            item = Issue()
                            item.Key = Newtonsoft.Json.Linq.Extensions.Value[
                                String](issue["key"])
                            fields = issue["fields"]
                            item.Updated = Newtonsoft.Json.Linq.Extensions.Value[
                                DateTime](fields["updated"])

                            # transform seconds to hours
                            estimate = Newtonsoft.Json.Linq.Extensions.Value[
                                System.Object](fields["timeoriginalestimate"])

                            if estimate is not None:
                                estimate = Newtonsoft.Json.Linq.Extensions.Value[
                                    Decimal](fields["timeoriginalestimate"])
                                estimate = estimate / (60.0 * 60.0)

                            item.TimeOriginalEstimate = estimate
                            status = fields["status"]
                            item.Status = Newtonsoft.Json.Linq.Extensions.Value[
                                String](status["name"])
                            item.Summary = Newtonsoft.Json.Linq.Extensions.Value[
                                String](fields["summary"])
                            type = fields["issuetype"]
                            item.Type = Newtonsoft.Json.Linq.Extensions.Value[
                                String](type["name"])
                            item.Link = self.repository.ToString(
                            ) + "browse/" + item.Key

                            subTasks = fields["subtasks"]
                            item.SubTaskKeys = System.Linq.Enumerable.Cast[
                                JObject](subTasks).Select(
                                    lambda t: Newtonsoft.Json.Linq.Extensions.
                                    Value[String](t["key"])).ToArray[String]()
                            items.Add(item)

                        return items