eric6/Plugins/UiExtensionPlugins/Translator/TranslatorRequest.py

Mon, 02 Sep 2019 18:50:38 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Mon, 02 Sep 2019 18:50:38 +0200
branch
without_py2_and_pyqt4
changeset 7201
6b42677d7043
parent 7192
a22eee00b052
child 7229
53054eb5b15a
permissions
-rw-r--r--

Modified sources to be in line with the minimum Qt/PyQt requirement (v 5.9.0).

# -*- coding: utf-8 -*-

# Copyright (c) 2014 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a synchronous network request handler for translation
requests.
"""

from __future__ import unicode_literals

from PyQt5.QtCore import QObject, QEventLoop, QByteArray
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, \
    QNetworkReply

from E5Network.E5NetworkProxyFactory import proxyAuthenticationRequired


class TranslatorRequest(QObject):
    """
    Class implementing a synchronous network request handler for translation
    requests.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        """
        super(TranslatorRequest, self).__init__(parent)
        
        self.__contentTypes = {
            "form": b"application/x-www-form-urlencoded",
            "json": b"application/json",
        }
        
        self.__networkManager = QNetworkAccessManager(self)
        self.__networkManager.proxyAuthenticationRequired.connect(
            proxyAuthenticationRequired)
        
        self.__loop = QEventLoop()
        self.__networkManager.finished.connect(self.__loop.quit)
    
    def get(self, requestUrl, extraHeaders=None):
        """
        Public method to issue a GET request.
        
        @param requestUrl URL of the request (QUrl)
        @keyparam extraHeaders list of tuples of additional headers giving
            header name (string) and header value (string)
        @return server response (QByteArray) or error message (string)
        """
        request = QNetworkRequest(requestUrl)
        request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        if extraHeaders:
            for name, value in extraHeaders:
                request.setRawHeader(name, value)
        reply = self.__networkManager.get(request)
        if not self.__loop.isRunning():
            self.__loop.exec_()
        if reply.error() != QNetworkReply.NoError:
            return reply.errorString(), False
        else:
            return reply.readAll(), True
    
    def post(self, requestUrl, requestData, dataType="form",
             extraHeaders=None):
        """
        Public method to issue a POST request.
        
        @param requestUrl URL of the request (QUrl)
        @param requestData data of the request (QByteArray)
        @keyparam dataType type of the request data (string)
        @keyparam extraHeaders list of tuples of additional headers giving
            header name (string) and header value (string)
        @return tuple of server response (string) and flag indicating
            success (boolean)
        """
        request = QNetworkRequest(requestUrl)
        request.setRawHeader(b"User-Agent",
                             b"Mozilla/5.0")
        request.setRawHeader(b"Content-Type",
                             self.__contentTypes[dataType])
        request.setRawHeader(b"Content-Length",
                             QByteArray.number(requestData.size()))
        request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        if extraHeaders:
            for name, value in extraHeaders:
                request.setRawHeader(name, value)
        request.setUrl(requestUrl)
        reply = self.__networkManager.post(request, requestData)
        if not self.__loop.isRunning():
            self.__loop.exec_()
        if reply.error() != QNetworkReply.NoError:
            return reply.errorString(), False
        else:
            return str(reply.readAll(), "utf-8", "replace"), True

eric ide

mercurial