Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8252201
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T00:29:51+00:00 2026-06-08T00:29:51+00:00

Ok, This should be simple, since people do it all the time. I want

  • 0

Ok,

This should be simple, since people do it all the time. I want to get the body of a POST request sent a twisted Agent. This is created with a twisted FileBodyProducer. On the server side, I get a request object for my render_POST method.

How do I retrieve the body?

server:

from twisted.web import server, resource
from twisted.internet import reactor


class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        return "{0}".format(request.args.keys())
    def render_POST(self, request):
        return "{0}".format(request.data)
        with open(request.args['filename'][0], 'rb') as fd:
            fd.write(request.write())

site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()

client:

from StringIO import StringIO

from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

from twisted.web.client import FileBodyProducer
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from pprint import pformat

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
            print display
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print 'Finished receiving body:', reason.getErrorMessage()
        self.finished.callback(None)

agent = Agent(reactor)
body = FileBodyProducer(StringIO("hello, world"))
d = agent.request(
    'POST',
    'http://127.0.0.1:8080/',
    Headers({'User-Agent': ['Twisted Web Client Example'],
             'Content-Type': ['text/x-greeting']}),
    body)

def cbRequest(response):
    print 'Response version:', response.version
    print 'Response code:', response.code
    print 'Response phrase:', response.phrase
    print 'Response headers:'
    print pformat(list(response.headers.getAllRawHeaders()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

The only docs I can find for setting up the consumer side leave something to be desired. Primarily, how can a consumer use the write(data) method to receive results?

Which bit am I missing to plug these two components together?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T00:29:52+00:00Added an answer on June 8, 2026 at 12:29 am

    All right, so it’s as simple as calling request.content.read(). This, as far as I can tell, is undocumented in the API.

    Here’s the updated code for the client:

    from twisted.internet import reactor
    from twisted.web.client import Agent
    from twisted.web.http_headers import Headers
    
    from twisted.web.client import FileBodyProducer
    from twisted.internet.defer import Deferred
    from twisted.internet.protocol import Protocol
    from pprint import pformat
    
    class BeginningPrinter(Protocol):
        def __init__(self, finished):
            self.finished = finished
            self.remaining = 1024 * 10
    
        def dataReceived(self, bytes):
            if self.remaining:
                display = bytes[:self.remaining]
                print 'Some data received:'
                print display
                self.remaining -= len(display)
    
        def connectionLost(self, reason):
            print 'Finished receiving body:', reason.getErrorMessage()
            self.finished.callback(None)
    
    class SaveContents(Protocol):
        def __init__(self, finished, filesize, filename):
            self.finished = finished
            self.remaining = filesize
            self.outfile = open(filename, 'wb')
    
        def dataReceived(self, bytes):
            if self.remaining:
                display = bytes[:self.remaining]
                self.outfile.write(display)
                self.remaining -= len(display)
            else:
                self.outfile.close()
    
        def connectionLost(self, reason):
            print 'Finished receiving body:', reason.getErrorMessage()
            self.outfile.close()
            self.finished.callback(None)
    
    agent = Agent(reactor)
    f = open('70935-new_barcode.pdf', 'rb')
    body = FileBodyProducer(f)
    d = agent.request(
        'POST',
        'http://127.0.0.1:8080?filename=test.pdf',
        Headers({'User-Agent': ['Twisted Web Client Example'],
                 'Content-Type': ['multipart/form-data; boundary=1024'.format()]}),
        body)
    
    def cbRequest(response):
        print 'Response version:', response.version
        print 'Response code:', response.code
        print 'Response phrase:', response.phrase
        print 'Response headers:'
        print 'Response length:', response.length
        print pformat(list(response.headers.getAllRawHeaders()))
        finished = Deferred()
        response.deliverBody(SaveContents(finished, response.length, 'test2.pdf'))
        return finished
    d.addCallback(cbRequest)
    
    def cbShutdown(ignored):
        reactor.stop()
    d.addBoth(cbShutdown)
    
    reactor.run()
    

    And here’s the server:

    from twisted.web import server, resource
    from twisted.internet import reactor
    import os
    
    # multi part encoding example: http://marianoiglesias.com.ar/python/file-uploading-with-multi-part-encoding-using-twisted/
    class Simple(resource.Resource):
        isLeaf = True
        def render_GET(self, request):
            return "{0}".format(request.args.keys())
        def render_POST(self, request):
            with open(request.args['filename'][0], 'wb') as fd:
                fd.write(request.content.read())
            request.setHeader('Content-Length', os.stat(request.args['filename'][0]).st_size)
            with open(request.args['filename'][0], 'rb') as fd:
                request.write(fd.read())
            request.finish()
            return server.NOT_DONE_YET
    
    site = server.Site(Simple())
    reactor.listenTCP(8080, site)
    reactor.run()
    

    I can now write the file contents I receive, and read back the results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This should be simple, yet I can't get it to work. I have a
I think this should be simple, but im having a real hard time finding
This should be simple, but I'm getting confused. I have a parent/child tables -
This should be simple task but i am not been able to find the
This should be simple, but the answer is eluding me. If I've got a
This should seem simple enough, but can't figure it out. I was porting a
This should be simple, but I am still lost. There is a very similar
Hey guys this should be simple, I'm just not seeing it, I would like
Seems like this should be simple, but powershell is winning another battle with me.
I think this should be simple but I am having some difficulty implementing it.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.