<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[QHttpMultiPart generates SIGSEGV when used multiple times]]></title><description><![CDATA[<p dir="auto">Hello Everyone!<br />
Using the following code, I am trying to upload images to a FastAPI http server:</p>
<pre><code>from pathlib import Path
import sys
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QLineEdit, QPushButton, QTextEdit, QFileDialog, \
    QApplication
from PyQt5.QtCore import pyqtSignal, QObject, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QHttpMultiPart, QHttpPart


class Client(QObject):
    replyReceived = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.nam = QNetworkAccessManager()
        self.nam.finished.connect(self.on_reply)

    def make_request(self, url, data, filename):
        print(f"Uploading file to {url}")
        self.request = QNetworkRequest(url)
        self.multipart = QHttpMultiPart(QHttpMultiPart.FormDataType)
        for key, value in (data or {}).items():
            http_part = QHttpPart()
            http_part.setHeader(
                QNetworkRequest.ContentDispositionHeader,
                f'form-data; name="{key}"'
            )
            http_part.setBody(value.encode('utf-8'))
            self.multipart.append(http_part)

        if filename:
            file_part = QHttpPart()
            filedata = open(filename, 'rb').read()
            file_part.setHeader(
                QNetworkRequest.ContentDispositionHeader,
                f'form-data; name="uploaded_file"; filename="{Path(filename).name}"'
            )
            file_part.setBody(filedata)
            self.multipart.append(file_part)

        self.nam.post(self.request, self.multipart)

    def on_reply(self, reply):
        reply_bytes = reply.readAll()
        reply_string = bytes(reply_bytes).decode('utf-8')
        self.replyReceived.emit(reply_string)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        widget = QWidget(minimumWidth=600)
        self.setCentralWidget(widget)
        widget.setLayout(QVBoxLayout())
        self.url = QLineEdit('http://127.0.0.1:8000/photos')
        self.fname = QPushButton('(Choose File...)', clicked=self.on_file_btn)
        submit = QPushButton('Send File', clicked=self.submit)
        response = QTextEdit(readOnly=True)
        for w in (self.url, self.fname, submit, response):
            widget.layout().addWidget(w)
        self.poster = Client()
        self.poster.replyReceived.connect(response.setText)
        self.show()

    def on_file_btn(self):
        filename, accepted = QFileDialog.getOpenFileName()
        if accepted:
            self.fname.setText(filename)

    def submit(self):
        url = QUrl(self.url.text())
        for i in range(0, 1):
            filename = '205520_20220911191143.png'
            if filename == '(No File)':
                filename = None
            data = {'var1': 'spam'}
            self.poster.make_request(url, data, filename)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec())
</code></pre>
<p dir="auto">If used once, this works as intended. However if I increase the steps in <code>line 71</code> to <code>range(0, 10)</code> for examle, I get:<br />
<code>Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)</code>.<br />
I believe that there is something blocking and objects are being deleted in the background, however I am unable to solve the problem here.<br />
I would be more than grateful if someone could give more insight to my issue!<br />
Thank you in advance!<br />
Boris</p>
]]></description><link>https://forum.qt.io/topic/139346/qhttpmultipart-generates-sigsegv-when-used-multiple-times</link><generator>RSS for Node</generator><lastBuildDate>Thu, 05 Nov 2026 03:24:47 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/139346.rss" rel="self" type="application/rss+xml"/><pubDate>Thu, 15 Sep 2022 20:18:33 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to QHttpMultiPart generates SIGSEGV when used multiple times on Fri, 16 Sep 2022 20:40:52 GMT]]></title><description><![CDATA[<p dir="auto">I also found this <a href="https://github.com/mbruel/qHttpPostFile/blob/master/HttpPoster.cpp#L54" target="_blank" rel="noopener noreferrer nofollow ugc">https://github.com/mbruel/qHttpPostFile/blob/master/HttpPoster.cpp#L54</a>, which in my case translates to :</p>
<pre><code>from pathlib import Path
import sys
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QLineEdit, QPushButton, QTextEdit, QFileDialog, \
    QApplication
from PyQt5.QtCore import pyqtSignal, QObject, QUrl, QEventLoop, QFile
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QHttpMultiPart, QHttpPart


class Client(QObject):
    replyReceived = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.nam = QNetworkAccessManager()
        self.nam.finished.connect(self.on_reply)

    def _create_multipart(self, url, data, filename):
        multipart = QHttpMultiPart(QHttpMultiPart.FormDataType)
        for key, value in (data or {}).items():
            http_part = QHttpPart()
            http_part.setHeader(
                QNetworkRequest.ContentDispositionHeader,
                f'form-data; name="{key}"'
            )
            http_part.setBody(value.encode('utf-8'))
            multipart.append(http_part)

        if filename:
            file_part = QHttpPart()
            filedata = open(filename, 'rb').read()
            file_part.setHeader(
                QNetworkRequest.ContentDispositionHeader,
                f'form-data; name="uploaded_file"; filename="{Path(filename).name}"'
            )
            file_part.setBody(filedata)
            multipart.append(file_part)
        return multipart
        # self.nam.post(request, multipart)
        # self.requests.append(request)
        # self.multiparts.append(multipart)

    def upload(self, url, data, filename):
        url = QUrl(url)
        multipart = self._create_multipart(url=url, data=data, filename=filename)
        request = QNetworkRequest(url)
        reply = self.nam.post(request, multipart)
        multipart.setParent(reply)
        print(f'Uploading file to {url}')


    def on_reply(self, reply):
        reply_bytes = reply.readAll()
        reply_string = bytes(reply_bytes).decode('utf-8')
        print(reply_string)
        self.replyReceived.emit(reply_string)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        widget = QWidget(minimumWidth=600)
        self.setCentralWidget(widget)
        widget.setLayout(QVBoxLayout())
        self.url = QLineEdit('http://127.0.0.1:8000/photos')
        self.fname = QPushButton('(Choose File...)', clicked=self.on_file_btn)
        submit = QPushButton('Send File', clicked=self.submit)
        response = QTextEdit(readOnly=True)
        for w in (self.url, self.fname, submit, response):
            widget.layout().addWidget(w)
        self.poster = Client()
        self.poster.replyReceived.connect(response.setText)
        self.show()

    def on_file_btn(self):
        filename, accepted = QFileDialog.getOpenFileName()
        if accepted:
            self.fname.setText(filename)

    def submit(self):
        url = QUrl(self.url.text())
        for i in range(0, 10):
            filename = '205520_20220911191143.png'
            if filename == '(No File)':
                filename = None
            data = {'var1': 'spam'}
            self.poster.upload(url, data, filename)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec())
</code></pre>
<p dir="auto">This method seems to work well (at least for my tests so far)</p>
]]></description><link>https://forum.qt.io/post/729074</link><guid isPermaLink="true">https://forum.qt.io/post/729074</guid><dc:creator><![CDATA[borisruna]]></dc:creator><pubDate>Fri, 16 Sep 2022 20:40:52 GMT</pubDate></item><item><title><![CDATA[Reply to QHttpMultiPart generates SIGSEGV when used multiple times on Fri, 16 Sep 2022 19:33:06 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/borisruna">@<bdi>borisruna</bdi></a> said in <a href="/post/728890">QHttpMultiPart generates SIGSEGV when used multiple times</a>:</p>
<blockquote>
<p dir="auto">QHttpMultiPart</p>
</blockquote>
<p dir="auto">With the great help of <a href="https://github.com/The-Compiler" target="_blank" rel="noopener noreferrer nofollow ugc">"The Compiler / Florian Bruhin"</a> from #qt-pyside on libera.chat, using <code>gdb -ex r --args python3 app.py</code> , we got the following result:</p>
<pre><code>#0  0x00007ffff59b5807 in QMetaObject::cast(QObject const*) const () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Core.so.5
No symbol table info available.
#1  0x00007ffff58e4dec in QNonContiguousByteDeviceFactory::createShared(QIODevice*) () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Core.so.5
No symbol table info available.
#2  0x00007ffff21eb1cd in QNetworkReplyHttpImplPrivate::createUploadByteDevice() () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5
No symbol table info available.
#3  0x00007ffff21f18ef in QNetworkReplyHttpImplPrivate::postRequest(QNetworkRequest const&amp;) () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5
No symbol table info available.
#4  0x00007ffff21f25c2 in QNetworkReplyHttpImplPrivate::start(QNetworkRequest const&amp;) () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5
--Type &lt;RET&gt; for more, q to quit, c to continue without paging--
No symbol table info available.
#5  0x00007ffff21f28db in QNetworkReplyHttpImplPrivate::_q_startOperation() () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5
No symbol table info available.
#6  0x00007ffff228ffb9 in QNetworkReplyHttpImpl::qt_static_metacall(QObject*, QMetaObject::Call, int, void**) () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Network.so.5
No symbol table info available.
#7  0x00007ffff59dada3 in QObject::event(QEvent*) () from /home/b/test/venv/lib/python3.8/site-packages/PyQt5/Qt5/lib/libQt5Core.so.5
No symbol table info available.
</code></pre>
<p dir="auto">and concluded that objects are garbage collected by Python during the upload, while Qt still needs them.<br />
One suggestion was to store the requests and multipart objects in a temporary list, however this would need then a proper cleanup to avoid a memory leak.<br />
Still working on this, will reply when finished. However if someone has other suggestions I would be more than happy to discuss them.<br />
Once again, many thanks to "The - Compiler" !</p>
]]></description><link>https://forum.qt.io/post/729069</link><guid isPermaLink="true">https://forum.qt.io/post/729069</guid><dc:creator><![CDATA[borisruna]]></dc:creator><pubDate>Fri, 16 Sep 2022 19:33:06 GMT</pubDate></item></channel></rss>