PyQt5 和 Django:如何使用 HTTP 请求(Multipart-form)上传图像?

时间:2023-03-12
本文介绍了PyQt5 和 Django:如何使用 HTTP 请求(Multipart-form)上传图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

目前我正在创建一个卖家应用程序,卖家可以在其中上传菜单图片和一些附加信息,例如价格和菜单名称.但我坚持使用 POST 请求方法,因为此时我必须上传带有一些文本数据的图像,而不仅仅是文本数据.

currently I am working in a project to create a seller application where the seller can upload the menu picture and some additional information such as the price and the name of the menu. but I stuck at the POST request method because in this time I have to upload an image with some text data instead of only text data.

我正在使用 PyQt5.

I am using PyQt5.

这是我的 API 网络服务器.我正在使用 Django Rest Framework 来构建它.

This is my API web server. I am using Django Rest Framework to build that.

[

这是菜单模型:

class Menu(models.Model):
    image = models.ImageField(upload_to=path_and_rename)
    name = models.CharField(max_length=100)
    price = models.IntegerField()
    category = models.IntegerField()
    availability = models.BooleanField(default=False)
    # booked = models.IntegerField()
    sellerID = models.ForeignKey(Seller, on_delete=models.PROTECT)

这是菜单序列化程序:

class MenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Menu
        fields = ('id', 'image', 'name', 'price', 
                  'category','availability', 'sellerID')

这是菜单视图集:

class MenuViewset(viewsets.ModelViewSet):
    queryset = models.Menu.objects.all()
    serializer_class = serializers.MenuSerializer

我已经尝试过这个答案中的方法:这里

I have tried to the method in this answer: here

这是我对该方法的实现:

This is my implementation to that method:

def upload(self):
    file1 = QFile("/home/shalahuddin/Desktop/jamu.jpg")
    file1.open(QFile.ReadOnly)
    url = "http://127.0.0.1:8000/api/menu/"

    nama = QByteArray()
    nama.append("ABCD")

    harga = QByteArray()
    harga.append(str(999))

    kategori = QByteArray()
    kategori.append(str(0))

    ada = QByteArray()
    ada.append(str(True))

    idseller = QByteArray()
    idseller.append(str(2))


    data = {"name": nama, "price": harga, "category": kategori, "availability": ada, "sellerID": idseller}
    files = {"image": file1}
    multipart = self.construct_multipart(data, files)
    request_qt = QNetworkRequest(QUrl(url))
    request_qt.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader,
                         'multipart/form-data; boundary=%s' % multipart.boundary())
    self.manager = QtNetwork.QNetworkAccessManager()
    self.manager.finished.connect(self.handleResponseMenu)
    self.manager.post(request_qt, multipart)

def handleResponseMenu(self, reply):
    er = reply.error()
    data = json.loads(str(reply.readAll(), 'utf-8'))
    file = open("/home/shalahuddin/Desktop/testfile.txt", "w")

    file.write(str(reply))
    if er == QtNetwork.QNetworkReply.NoError:
        bytes_string = reply.readAll()
        data = json.loads(str(bytes_string, 'utf-8'))
        # print(data)
        QMessageBox.information(self, "Menu", "Upload Success!")

    else:
        errorMessage = "Error occured: " + str(er) + "
" + str(reply.errorString())
        QMessageBox.critical(self, "Error Done", errorMessage)

def construct_multipart(self, data, files):
    multiPart = QHttpMultiPart(QHttpMultiPart.FormDataType)
    for key, value in data.items():
        textPart = QtNetwork.QHttpPart()
        textPart.setHeader(QNetworkRequest.ContentDispositionHeader,
                           "form-data; name="%s"" % key)
        textPart.setBody(value)
        multiPart.append(textPart)

    for key, file in files.items():
        imagePart = QtNetwork.QHttpPart()
        # imagePart.setHeader(QNetworkRequest::ContentTypeHeader, ...);
        fileName = QFileInfo(file.fileName()).fileName()
        imagePart.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader,
                            "form-data; name="%s"; filename="%s"" % (key, fileName))
        imagePart.setBodyDevice(file)
        multiPart.append(imagePart)
    return multiPart

但是我得到了错误 302 Bad Request 结果.我得到的 JSON 数据是:

But I got error 302 Bad Request as the result. The JSON data that I get is:

{
  'image': ['No file was submitted.'], 
  'name': ['Ensure this field has no more than 100 characters.', 
           'Null characters are not allowed.'], 
  'price': ['This field is required.'], 
  'category': ['This field is required.'], 
  'sellerID': ['This field is required.']
}

因此,我想知道问题出在哪里?我试图反复追踪它,但仍然没有给出答案.这是我第一次使用多部分请求.

Therefore, I would like to know where is the problem? I have tried to trace it repeatedly but still, give no answer. This is my first time to using multipart request.

推荐答案

在下面的示例中,我将向您展示如何创建查询:

In the following example I show you create the query:

import json
from PyQt5 import QtCore, QtNetwork, QtWidgets

class MenuWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MenuWidget, self).__init__(parent)
        self._manager = QtNetwork.QNetworkAccessManager()
        self._manager.finished.connect(self.handleResults)

        self.init_ui()

    def init_ui(self):
        self.filepath_lineedit = QtWidgets.QLineEdit()
        select_button = QtWidgets.QPushButton(
            text="Select File",
            clicked=self.select_file
        )
        self.name_lineedit = QtWidgets.QLineEdit()
        self.price_spinbox = QtWidgets.QSpinBox()
        self.category_spinbox = QtWidgets.QSpinBox()
        self.availability_checkbox = QtWidgets.QCheckBox()
        self.seller_id_spinbox = QtWidgets.QSpinBox()
        self.log_textedit = QtWidgets.QTextBrowser()
        upload_button = QtWidgets.QPushButton(
            text="Upload",
            clicked=self.upload
        )

        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.filepath_lineedit)
        hlay.addWidget(select_button)
        lay = QtWidgets.QFormLayout(self)
        lay.addRow("Image:", hlay)
        lay.addRow("Name:", self.name_lineedit)
        lay.addRow("Price:", self.price_spinbox)
        lay.addRow("Category:", self.category_spinbox)
        lay.addRow("Availability:", self.availability_checkbox)
        lay.addRow("SellerID:", self.seller_id_spinbox)
        lay.addRow(self.log_textedit)
        lay.addRow(upload_button)

    @QtCore.pyqtSlot()
    def select_file(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            self, 
            "Open Image", 
            QtCore.QDir.currentPath(), 
            "Image Files (*.png *.jpg *.bmp)"
        )
        if filename:
            self.filepath_lineedit.setText(filename)

    @QtCore.pyqtSlot()
    def upload(self):   
        data = {
            "name": self.name_lineedit.text(),
            "price": self.price_spinbox.value(),
            "category": self.category_spinbox.value(),
            "availability": self.availability_checkbox.isChecked(),
            "sellerID": self.seller_id_spinbox.value()
        }
        path = self.filepath_lineedit.text()
        files = {"image": path}
        multi_part = self.construct_multipart(data, files)
        if multi_part:
            url = QtCore.QUrl("http://127.0.0.1:8000/api/menu/")
            request = QtNetwork.QNetworkRequest(url)
            reply = self._manager.post(request, multi_part)
            multi_part.setParent(reply)

    @QtCore.pyqtSlot(QtNetwork.QNetworkReply)
    def handleResults(self, reply):
        parsed = json.loads(reply.readAll().data())
        text = json.dumps(parsed, indent=4, sort_keys=True)
        self.log_textedit.setText(text)
        if reply.error() == QtNetwork.QNetworkReply.NoError:
            QtWidgets.QMessageBox.information(self, "Menu", "Upload Success!")
        else:
            errorMessage = "Error occured: {}".format(reply.errorString())
            QMessageBox.critical(self, "Error Done", errorMessage)
        reply.deleteLater()

    def construct_multipart(self, data, files):
        multi_part = QtNetwork.QHttpMultiPart(QtNetwork.QHttpMultiPart.FormDataType)
        for key, value in data.items():
            post_part = QtNetwork.QHttpPart()
            post_part.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader, 
                "form-data; name="{}"".format(key))
            post_part.setBody(str(value).encode())
            multi_part.append(post_part)
        for field, filepath in  files.items():
            file = QtCore.QFile(filepath)
            if not file.open(QtCore.QIODevice.ReadOnly):
                break
            post_part = QtNetwork.QHttpPart()
            post_part.setHeader(QtNetwork.QNetworkRequest.ContentDispositionHeader,
                "form-data; name="{}"; filename="{}"".format(field, file.fileName()))
            post_part.setBodyDevice(file)
            file.setParent(multi_part)
            multi_part.append(post_part)
        return  multi_part


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MenuWidget()
    w.show()
    sys.exit(app.exec_())

这篇关于PyQt5 和 Django:如何使用 HTTP 请求(Multipart-form)上传图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:授予对 Cam & 的访问权限将 Python 用于 PyQt WebEngine 的麦克风 下一篇:如何结合这两个代码?(python图像查看器+鼠标拖动图像ROI裁剪)

相关文章