开发者

python 3 https posting very slow

I have a script which logs in via https using python 3 and FancyURLopener. So I am doing this:

from urllib.request import FancyURLopener, urlopen
from urllib.parse import urlencode
import re, sys

class SMS:

    login_url = "url1"
    login_act = "url2"
    comp_url = "url3"
    comp_act = "url4"
    LEN = 100

    def __init__(self, phone_num, password):
        self.phone_num = phone_num
        self.password = password
        self.opener = FancyURLopener()
        resp = self.opener.open(SMS.login_url)
        cookie = ""
        for x, y in resp.headers.items():
            if x == "Set-Cookie":
                cookie += y + "; "
        cookie = cookie[:-2]            
        self.opener.addheader("Cookie", cookie)
        print("--login")
        self.login()

    def login(self):
        di = { "action":"", "refid":"", "continuation":"",\
"username":self.phone_num, "password":self.password, "image.x":"45", "image.y":"18"}
        resp = self.opener.open(SMS.login_act, urlencode(di))

    def send(self, to, mes开发者_开发百科sage):
        print("--sending")
        if len(message) > 100:
            print("Message length too long; Not send.")
            return -1
        resp = self.opener.open(SMS.comp_url).read().decode("windows-1251")
        pattern1 = "<input type=\"hidden\" name=\"daycreditsmsleft\" value=\"(\d+)\""
        pattern2 = "<input type=\"HIDDEN\" name=\"smssenttime\" value=\"(\d+)\""
        post = {"brand":"", "daycreditsmsleft":re.search(pattern1, resp).groups()[0],\
"process":"true", "btnSendSMS.x":"75", "btnSendSMS.y":"23", "model":"0",\
"smssenttime":re.search(pattern2, resp).groups()[0], "remainingChars": str(SMS.LEN - len(message)),\
"reply2inbox":"false", "selReceiverName":"", "txtareaMessage":message, "receiverPhoneNum":to}
        if post["daycreditsmsleft"] == 0:
            print("No more messages; Not send")
            return -1
        resp = self.opener.open(SMS.comp_act, urlencode(post) )

I will then use it like this:

s = SMS("telephone_num", "pass")
s.send(tel, message)

The problem is that the POST request is too slow. It takes more than 20 seconds to log in. In the whole script there are 2 POST requests so it actually runs near a minute. How to optimize it?

I also noticed that the messages are received before the program ends.


My guess is that there is something subtly different in the requests, that make your server take a very long time in processing the request.

If you are the writer of the server, this should be easy to verify. If not you probably have to use some sort of tracing program so you can see when the request is done from the Python-side and seeing when a response comes back, and comparing that with a request from your browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜