Python usage: post an HTTP request and schedule a task

Source: Internet
Author: User

The content is also available in the http://iihero.cn, here.
Recently, I used my free time to look at some modules in Python. I feel this feature is so good and so powerful.
(1) Use it to post an HTTP request:

Import urllib, urllib2, cookielib
Def post3 ():
# For mail.sina.com.cn

Cj = cookielib. cookiejar ()
Url_login = 'HTTP: // mail.sina.com.cn/cgi-bin/login.cgi'
Body = ('logintype', 'login'), ('U', 'username '),
('Psw ','********'))
Opener = urllib2.build _ opener (urllib2.httpcookieprocessor (CJ ))
# Opener. addheaders = [('user-agent', 'Opera/123')]
Opener. addheaders = [('user-agent ',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) ')]
Urllib2.install _ opener (opener)
Req = urllib2.request (url_login, urllib. urlencode (body ))
U = urllib2.urlopen (req)
Print U. Read (). Decode ('utf-8'). encode ('gbk ')

 

In the afternoon, I tried Python's HTTP-related class method and used the above Code to log on to Sina mail. I tried it for a while,
The most important thing is the User-Agent, which is supported by the above two browsers. It is estimated that the Default User-Agent of Python cannot be verified by Sina.com.

It is quite convenient for python to write this HTTP method code.

(2) Write a small task execution task on a regular basis. This is a single-threaded version, and it is easy to change it to multiple threads.

 

#! /Usr/bin/ENV Python
# Coding = UTF-8

Import thread, time

Def task ():
'''
Here we can execute some task to be scheduled every n seconds
'''
Print "task doing ......"

Def main (n ):
T = time. Time ()
Start_t = T
End_t = start_t + 60*60*72
# While (T <end_t ):
While true:
Task ()
Time. Sleep (N)
T = time. Time ()

If _ name _ = "_ main __":

Try:
Main (5)
Except t keyboardinterrupt:
Print "system exit ......"
SYS. Exit (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.