Example of asynchronous HTTP request using QtNetwork in PyQt

Source: Internet
Author: User
Tags bind call back http request

Introduction

Recently, we need to request a link in PyQt because urllib2 is simple and directly used for processing, but urllib2 will cause the GUI interface to die when there is a delay. So today we are studying the QtNetwork module.

Requests in QtNetwork are asynchronous in PyQt.

Simple request QHttp

Initiate a GET request

PyQt4.QtNetwork. QHttp can initiate a simple request. It should be noted that this object needs to set the request host by calling setHost and then calling get/post to pass in the path for normal use.

The code is as follows: Copy code

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
From PyQt4 import QtGui, QtCore, QtNetwork


Class MainWidget (QtGui. QWidget ):

Def _ init _ (self, parent = None ):
Super (MainWidget, self). _ init _ (parent = parent)

Self. http = QtNetwork. QHttp (parent = self)

# Bind a done signal
Self. http. done. connect (self. on_req_done)

Self. url = QtCore. QUrl ("http://linuxzen.com /")

# Set hosts
Self. http. setHost (self. url. host (), self. url. port (80 ))
Self. getId = self. http. get (self. url. path ())

Def on_req_done (self, error ):
If not error:
Print "Success"
Print self. http. readAll ()
Else:
Print "Error"


If _ name _ = "_ main __":
App = QtGui. QApplication ([])
Main = MainWidget ()
Main. show ()
App.exe c _()

Save files
If you want to download an object, you can pass a QtCore. QFile object to the get method and save the request content to the file.

The code is as follows: Copy code

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

From PyQt4 import QtGui, QtCore, QtNetwork


Class MainWidget (QtGui. QWidget ):

Def _ init _ (self, parent = None ):
Super (MainWidget, self). _ init _ (parent = parent)

Self. http = QtNetwork. QHttp (parent = self)
Self. http. done. connect (self. on_req_done)

Self. url = QtCore. QUrl ("http://www.linuxzen.com /")
Self. http. setHost (self. url. host (), self. url. port (80 ))
Self. out = QtCore. QFile ("./test ")
Self. getId = self. http. get (self. url. path (), self. out)

Def on_req_done (self, error ):
# Print self. http. readAll (), error
If not error:
Print "Success"
Else:
Print "Error"


If _ name _ = "_ main __":
App = QtGui. QApplication ([])
Main = MainWidget ()
Main. show ()
App.exe c _()

The code above saves the requested content to the test file in the current directory.

Process header information
One requirement is that a link will return a 301 or 302 jump, but PyQt4.QtNetwork. QHttp does not implement automatic jump. We need to automatically determine the header information for jump.

We can bind the signal of PyQt4.QtNetwork. QHttp. responseHeaderReceived to process the header information. This signal will be sent to the slot to an instance of PyQt4.QtNetwork. QHttpResponseHeader.

Do you know the status and capture the Location header to redirect?

The code is as follows: Copy code

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
#
From PyQt4 import QtGui, QtCore, QtNetwork


Class MainWidget (QtGui. QWidget ):

Def _ init _ (self, parent = None ):
Super (MainWidget, self). _ init _ (parent = parent)

Self. http = QtNetwork. QHttp (parent = self)
Self. http. done. connect (self. on_req_done)
Self. http. responseHeaderReceived. connect (self. on_response_header)

Self. url = QtCore. QUrl ("http://t.cn/zTocACq ")
Self. http. setHost (self. url. host (), self. url. port (80 ))
Self. out = QtCore. QFile ("./test ")
Self. getId = self. http. get (self. url. path (), self. out)

Def on_response_header (self, response_header ):
If response_header.statusCode () in [301,302]:
Location = response_header.value ("Location ")
Print "Redirect to:", location
Self. getId = self. http. get (location, self. out)
Tmp = QtCore. QUrl (location)
If str (tmp. host ()):
Self. url = tmp
Self. http. setHost (self. url. host (), self. url. port (80 ))
Else:
Self. url. setPath (location)
Self. http. get (self. url. path () or "/", self. out)

Def on_req_done (self, error ):
If not error:
Print "Success"
Print self. http. readAll ()
Else:
Print "Error"


If _ name _ = "_ main __":
App = QtGui. QApplication ([])
Main = MainWidget ()
Main. show ()
App.exe c _()

Run the above code and you will see the following output

Redirect to: http://www.111cn.net

Success
Processing parameters
If the url of your GET request is sent to QUrl with parameters, QUrl. path () will not return the path with parameters and need to be processed by yourself. See the following processing functions.

The code is as follows: Copy code
Def get_query_string (self ):
Return self. url. queryPairDelimiter (). join (
"{0} {1} {2}". format (k, self. url. queryValueDelimiter (), v)
For k, v in self. url. queryItems ()
        )

You can add it when you request it.

The code is as follows: Copy code
Self. http. get (self. url. path () + "? "+ Self. get_query_string ())

Process Cookie ---- QNetworkAccessManager
QHttp cannot automatically record cookies and set cookies. If this requirement is met, PyQt4.QtNetwork. QNetworkAccessManager is required.

The code is as follows: Copy code

The request method of QNetworkAccessManager is not to pass in a QString, but to an instance of PyQt4.QtNetwork. QNetworkRequest.

QNetworkAccessManager is also Asynchronous. You can bind the QNetworkAccessManager. finished signal. This signal will pass an instance of PyQt4.QtNetwork. QNetworkReply to the slot.

QNetworkAccessManager. setCookieJar can be used to set a PyQt4.QtNetwork. QNetworkCookieJar object to automatically save and set cookies.

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
#
From PyQt4 import QtGui, QtCore, QtNetwork


Class MainWidget (QtGui. QWidget ):
Def _ init _ (self, parent = None ):
Super (MainWidget, self). _ init _ (parent)
Self. _ cookiejar = QtNetwork. QNetworkCookieJar (parent = self)

Self. manager = QtNetwork. QNetworkAccessManager (parent = self)

Self. manager. setCookieJar (self. _ cookiejar)

Self. manager. finished. connect (self. on_reply)

Self. req = QtNetwork. QNetworkRequest (
QtCore. QUrl ("http://www.google.com.hk "))

Self. manager. get (self. req)

Def on_reply (self, reply ):
Print reply, self. _ cookiejar. allCookies ()
Print reply. rawHeaderList ()
# Print reply. readAll ()


If _ name _ = "_ main __":
App = QtGui. QApplication ([])
Widget = MainWidget ()
Widget. show ()
App.exe c _()

In this way, you can carry a Cookie to request requests that require Cookie authentication.

Summary

There are still a lot of content that will not be described one by one, such as using QProgressBar, adding header information, POST requests, and so on.

Here is a brief introduction to Qt's network request processing method. using urllib and other libraries in PyQt is obviously not a good solution, because it will cause the interface to die. however, PyQt4 is not very elegant. there are many things to call back and forth. but at least it will not cause the interface card to die.

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.