Http authorization

Sockets, TCP/IP, (XML-)RPC und ähnliche Themen gehören in dieses Forum
Antworten
taake
User
Beiträge: 125
Registriert: Donnerstag 14. Oktober 2010, 08:49

Moin ich hab ein kleines Prob mit dem Auth bei nem Formupload.

Code: Alles auswählen


for numbers in artikelliste:   
    for path in path_array:
        if numbers[:-4] in path:
            print (numbers + path)
            class MultiPartForm(object):
                """Accumulate the data to be used when posting a form."""
                    
                def __init__(self):
                    self.form_fields = []
                    self.files = []
                    self.boundary = "127.0.0.1.1000.4336.1291319528.064.1"
                    return
    
                def get_content_type(self):
                    return 'multipart/form-data; boundary=%s' % self.boundary

                def add_field(self, name, value):
                    """Add a simple field to the form data."""
                    self.form_fields.append((name, value))
                    return

                def add_file(self, fieldname, filename, fileHandle, mimetype=None):
                    """Add a file to be uploaded."""
                    body = fileHandle.read()
                    if mimetype is None:
                        mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
                    self.files.append((fieldname, filename, mimetype, body))
                    return
    
                def __str__(self):
                    """Return a string representing the form data, including attached files."""
                    # Build a list of lists, each containing "lines" of the
                    # request.  Each part is separated by a boundary string.
                    # Once the list is built, return a string where each
                    # line is separated by '\r\n'.  
                    parts = []
                    part_boundary = '--' + self.boundary
        
                    # Add the form fields
                    parts.extend(
                        [ part_boundary,
                         'Content-Disposition: form-data; name="%s"' % name,
                         '',
                         value,
                        ]
                        for name, value in self.form_fields
                        )
        
                    # Add the files to upload
                    parts.extend(
                        [ part_boundary,
                         'Content-Disposition: file; name="%s"; filename="%s"' % \
                            (field_name, filename),
                         'Content-Type: %s' % content_type,
                         '',
                         body,
                        ]
                        for field_name, filename, content_type, body in self.files
                        )
        
                    # Flatten the list and add closing boundary marker,
                    # then return CR+LF separated data
                    flattened = list(itertools.chain(*parts))
                    flattened.append('--' + self.boundary + '--')
                    flattened.append('')
                    return '\r\n'.join(flattened)

            if __name__ == '__main__':
                # Create the form with simple fields
                form = MultiPartForm()
                form.add_field('Sprachzeile', 'deutsch')
                form.add_field('txt_title', '******')
                form.add_field('action', 'bilderupload')
                form.add_field('job', 'artikelbildupload')
                form.add_field('navigat', 'navia')
                form.add_field('anzeigen', '1')
                form.add_field('artikel_nummer', numbers)
                             
                
                
                # Add a fake file
                form.add_file('bild', path, 
                              fileHandle=StringIO('Python developer and blogger.'))

                # Build the request
                request = urllib.request.Request('http://shop.*******/redaktion/index.php')
                request.add_header('User-agent', 'PyMOTW (http://www.doughellmann.com/PyMOTW/)')
                body = str(form)
                request.add_header('Authorization' , 'Basic *****************')
                request.add_header('Content-type', str.encode( form.get_content_type() ))
                request.add_header('Content-length', str.encode( str( len(body ) )))
                request.add_data(body)

                print()
                print('OUTGOING DATA:')
                print(request.get_data())

                print()
                print('SERVER RESPONSE:')
                print(bytes.decode(urllib.request.urlopen(request).read()))
Ich habs versucht indem ich wie oben zu sehen noch
request.add_header('Authorization' , 'Basic *****************')
mit eingebaut habe.

Allerdings lt. wireshark bekomme ich immer noch beim upload "HTTP/ 1.1 401 Authorization Reuired (text/html)"
Er läd dann nur ein leeres Bild noch...

Kann mir jemand sagen was da falsch läuft?

Außerdem bekomme ich noch den traceback:

SERVER RESPONSE:
Traceback (most recent call last):
File "D:\workbench\Webshop Bildsync\src\misspic.py", line 180, in <module>
print(bytes.decode(urllib.request.urlopen(request).read()))
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 314-317: invalid data
ms4py
User
Beiträge: 1178
Registriert: Montag 19. Januar 2009, 09:37

Schau dir mal die Beispiele im urllib2 Modul an, da gibt es eines mit Basic Auth...
http://docs.python.org/library/urllib2.html#examples
„Lieber von den Richtigen kritisiert als von den Falschen gelobt werden.“
Gerhard Kocher

http://ms4py.org/
taake
User
Beiträge: 125
Registriert: Donnerstag 14. Oktober 2010, 08:49

Passt, danke =)

Aber ein Problem hab ich noch:

Encapsulated multipart part: (image/jpeg)
Content-Disposition: file; name="bild"; filename="/home/user/python/webupload/\18926-00455.jpg"\r\n
Content-Type: image/jpeg\r\n\r\n
JPEG File Interchange Format
This is not a valid JFIF (JPEG) object
Dauerbaustelle
User
Beiträge: 996
Registriert: Mittwoch 9. Januar 2008, 13:48

Btw, bist du dir sicher, dass du Klassendefinitionen und Hauptprogrammcode (`__name__ == '__main__') in eine Schleife packen willst?!
taake
User
Beiträge: 125
Registriert: Donnerstag 14. Oktober 2010, 08:49

Habs hinbekommen, jedenfalls soweit das es aus meiner Sicht keine Probleme mehr gibt jedenfalls von Python aus.

Allerdings funtzt das ganze immer noch nicht so wie es sollte...

Werde dafür noch nen thread aufmachen, der Übersichtlichkeit halber und den hier verlinken.


Und ja hab nochmal ein paar Sachen geändert...


http://www.python-forum.de/viewtopic.php?f=3&t=24925
Antworten