久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

<small id='G5sbL'></small><noframes id='G5sbL'>

    <tfoot id='G5sbL'></tfoot>

      <bdo id='G5sbL'></bdo><ul id='G5sbL'></ul>
    <i id='G5sbL'><tr id='G5sbL'><dt id='G5sbL'><q id='G5sbL'><span id='G5sbL'><b id='G5sbL'><form id='G5sbL'><ins id='G5sbL'></ins><ul id='G5sbL'></ul><sub id='G5sbL'></sub></form><legend id='G5sbL'></legend><bdo id='G5sbL'><pre id='G5sbL'><center id='G5sbL'></center></pre></bdo></b><th id='G5sbL'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='G5sbL'><tfoot id='G5sbL'></tfoot><dl id='G5sbL'><fieldset id='G5sbL'></fieldset></dl></div>
    1. <legend id='G5sbL'><style id='G5sbL'><dir id='G5sbL'><q id='G5sbL'></q></dir></style></legend>
      1. PyQt5 和 Django:如何使用 HTTP 請求(Multipart-form)上傳

        PyQt5 and Django : How to Upload Image using HTTP Request ( Multipart-form )?(PyQt5 和 Django:如何使用 HTTP 請求(Multipart-form)上傳圖像?)
          <tbody id='g1CHo'></tbody>

          1. <small id='g1CHo'></small><noframes id='g1CHo'>

            <i id='g1CHo'><tr id='g1CHo'><dt id='g1CHo'><q id='g1CHo'><span id='g1CHo'><b id='g1CHo'><form id='g1CHo'><ins id='g1CHo'></ins><ul id='g1CHo'></ul><sub id='g1CHo'></sub></form><legend id='g1CHo'></legend><bdo id='g1CHo'><pre id='g1CHo'><center id='g1CHo'></center></pre></bdo></b><th id='g1CHo'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='g1CHo'><tfoot id='g1CHo'></tfoot><dl id='g1CHo'><fieldset id='g1CHo'></fieldset></dl></div>

              <tfoot id='g1CHo'></tfoot>

                  <bdo id='g1CHo'></bdo><ul id='g1CHo'></ul>
                • <legend id='g1CHo'><style id='g1CHo'><dir id='g1CHo'><q id='g1CHo'></q></dir></style></legend>
                  本文介紹了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)上傳圖像?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                  【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                  相關文檔推薦

                  How to bind a function to an Action from Qt menubar?(如何將函數綁定到 Qt 菜單欄中的操作?)
                  PyQt progress jumps to 100% after it starts(PyQt 啟動后進度躍升至 100%)
                  How to set yaxis tick label in a fixed position so that when i scroll left or right the yaxis tick label should be visible?(如何將 yaxis 刻度標簽設置在固定位置,以便當我向左或向右滾動時,yaxis 刻度標簽應該可見
                  `QImage` constructor has unknown keyword `data`(`QImage` 構造函數有未知關鍵字 `data`)
                  Change x-axis ticks to custom strings(將 x 軸刻度更改為自定義字符串)
                  How to show progress bar while saving file to excel in python?(如何在python中將文件保存為excel時顯示進度條?)
                  <i id='2TOs8'><tr id='2TOs8'><dt id='2TOs8'><q id='2TOs8'><span id='2TOs8'><b id='2TOs8'><form id='2TOs8'><ins id='2TOs8'></ins><ul id='2TOs8'></ul><sub id='2TOs8'></sub></form><legend id='2TOs8'></legend><bdo id='2TOs8'><pre id='2TOs8'><center id='2TOs8'></center></pre></bdo></b><th id='2TOs8'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='2TOs8'><tfoot id='2TOs8'></tfoot><dl id='2TOs8'><fieldset id='2TOs8'></fieldset></dl></div>
                    <legend id='2TOs8'><style id='2TOs8'><dir id='2TOs8'><q id='2TOs8'></q></dir></style></legend>

                        <tbody id='2TOs8'></tbody>
                      • <bdo id='2TOs8'></bdo><ul id='2TOs8'></ul>

                            <small id='2TOs8'></small><noframes id='2TOs8'>

                          1. <tfoot id='2TOs8'></tfoot>

                          2. 主站蜘蛛池模板: 天天干夜夜 | 黄色一级免费视频 | 岛国av噜噜噜久久久狠狠av | 黄色小说视频网站 | 中文在线观看免费视频 | 欧美一区| av不卡在线 | 日韩国产一区 | 中文在线播放 | 亚洲综合视频在线 | 日韩欧美第一页 | 国产乱码精品一区二区三 | 成人午夜网站 | 国产精品视频网站 | 成人一区二区三区 | 三级在线播放 | 国产精品久久久久久久久久久久久久久 | 欧美激情综合 | 欧美一级片在线观看 | 亚洲综合色网 | 免费视频a | 97在线免费视频 | 精品日韩| 中文字幕在线免费观看 | 色吧综合| 国产成人精品久久久 | 国产黄色av | www.亚洲成人 | 日日爽夜夜爽 | 午夜激情福利 | 天天干天天干天天干 | 亚洲综合天堂 | 精品亚洲国产成人av制服丝袜 | 五月天网址 | 色天使在线视频 | 亚洲天堂网在线观看 | 乱色av | 精品国产一区二区三 | 少妇高潮露脸国语对白 | 欧美日韩精品在线 | 青青青草视频 |