Python encoding file header

Как кодировать имя файла UTF8 для заголовков HTTP? (Питон, Джанго)

У меня проблема с HTTP-заголовками, они закодированы в ASCII, и я хочу предоставить представление для загрузки файлов, имена которых могут быть не ASCII.

response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), ) 

Я не хочу использовать статические файлы для одной и той же проблемы с именами файлов без ASCII, но в этом случае возникнет проблема с файловой системой и кодировкой имени файла. (Я не знаю цели.) Я уже пробовал urllib.quote(), но вызывает исключение KeyError. Возможно, я делаю что-то неправильно, но, возможно, это невозможно.

Я понимаю, что опоздал на несколько лет, но . исключение KeyError действительно меня беспокоит. Я не просто имею в виду «каждый раз, когда я сталкиваюсь с этой проблемой», я имею в виду, я отправил патч в Python, чтобы исправить это несколько лет назад, некоторое время спорил, потом решил, что они не хотят менять Python 2. Я действительно исправил эту проблему в Python 3, но они никогда не принимали мой патч в Python 2. Обходной путь — сначала .encode (‘utf-8’), а затем использовать urllib.quote. Но это для URL-кодирования, которое не является стандартным способом поместить их в заголовки.

6 ответов

Существует не совместимый способ сделать это. Некоторые браузеры реализуют проприетарные расширения (IE, Chrome), другие реализуют RFC 2231 (Firefox, Opera).

Обновление: по состоянию на ноябрь 2012 года все текущие настольные браузеры поддерживают кодировку, определенную в RFC 6266 и RFC 5987 (Safari >= 6, IE >= 9, Chrome, Firefox, Opera, Konqueror).

Читайте также:  Composer require php intl

Совсем недавно Джулиан создал для этой цели профиль RFC2231: datatracker.ietf.org/doc/draft-reschke-rfc2231-in-http

Применимо ли это для поддержки multipart / form-data, потому что сейчас я вижу необработанные байты UTF-8, отправленные в параметре ‘filename’ при загрузке файла из формы в Chrome

Не отправляйте имя файла в Content-Disposition. Невозможно настроить кросс-браузер (*) параметры не-ASCII-заголовка.

Вместо этого отправьте только «Content-Disposition: attachment» и оставьте имя файла в виде строки UTF-8, закодированной в URL-адресе в концевой (PATH_INFO) части вашего URL-адреса, чтобы браузер мог выбирать и использовать по умолчанию. URL-адреса UTF-8 обрабатываются гораздо более надежно браузерами, чем что-либо, что связано с Content-Disposition.

(*: на самом деле, нет даже текущего стандарта, который говорит, как это должно быть сделано, поскольку отношения между RFC 2616, 2231 и 2047 довольно дисфункциональны, то, что Джулиан пытается прояснить на уровне спецификации. поддержка браузера в отдаленном будущем.)

Так как этот ответ вышел, был выпущен RFC на эту тему. Следует отметить filename*= construct, которое поддерживается только новыми браузерами и гарантированно позволит вам использовать UTF-8, закодированное как в RFC 5987. tools.ietf.org/html/rfc6266#appendix-D

Обратите внимание, что в 2011 году RFC 6266 (особенно Приложение D) в этом вопросе было сказано и содержит конкретные рекомендации.

А именно, вы можете выпустить filename только с символами ASCII, а затем filename* с файловым именем формата RFC 5987 для тех агентов, которые его понимают.

Обычно это будет выглядеть как filename=»my-resume.pdf»; filename*=UTF-8»My%20R%C3%A9sum%C3%A9.pdf , где имя файла Unicode ( «My Résumé.pdf» ) закодировано в UTF-8, а затем в процентах (обратите внимание, НЕ используйте + для пробелов).

Пожалуйста, действительно прочитайте RFC 6266 и RFC 5987 (или используйте надежную и протестированную библиотеку, которая абстрагирует это для вас), так как мое резюме здесь не содержит важных деталей.

Я могу сказать, что у меня был успех с использованием нового (RFC 5987) формата указания заголовка, закодированного с помощью электронной почты form (RFC 2231). Я придумал следующее решение, основанное на коде из проекта django-sendfile.

import unicodedata from django.utils.http import urlquote def rfc5987_content_disposition(file_name): ascii_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore').decode() header = 'attachment; filename="<>"'.format(ascii_name) if ascii_name != file_name: quoted_name = urlquote(file_name) header += '; filename*=UTF-8\'\'<>'.format(quoted_name) return header # e.g. # request['Content-Disposition'] = rfc5987_content_disposition(file_name) 

Я только проверил свой код на Python 3.4 с Django 1.8. Таким образом, аналогичное решение в django-sendfile может вам лучше поменять.

Там есть длинный билет в джэкго-трекере, который подтверждает это, но патчи еще не были предложены afaict. К сожалению, это так близко к использованию надежной проверенной библиотеки, как я мог найти, пожалуйста, дайте мне знать, если есть лучшее решение.

Начиная с 2018 года, решение теперь доступно в Django 2.1 (после томления в течение семи лет в виде открытого билета). Вы можете использовать параметр as_attachment встроенный в FileResponse. Например, чтобы вернуть файл output_file с типом mime output_mime_type в качестве ответа HTTP:

response = FileResponse(open(output_file, 'rb'), as_attachment=True, content_type=output_mime_type) return response 

Или, если вы не можете использовать FileResponse , вы можете использовать соответствующую часть из ее источника для более непосредственного изменения Content-Disposition . Вот как выглядит этот источник в настоящее время:

from urllib.parse import quote try: document.file_name.encode('ascii') file_expr = 'filename="<>"'.format(filename) except UnicodeEncodeError: # Handle a non-ASCII filename file_expr = "filename*=utf-8''<>".format(quote(filename)) response['Content-Disposition'] = 'attachment; <>'.format(file_expr) 

Источник

PEP 263 – Defining Python Source Code Encodings

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding “unicode-escape”. This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the “unicode-escape” encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

or (using formats recognized by popular editors):

#!/usr/bin/python # vim: set fileencoding= : 

More precisely, the first or second line must match the following regular expression:

The first group of this expression is then interpreted as encoding name. If the encoding is unknown to Python, an error is raised during compilation. There must not be any Python statement on the line that contains the encoding declaration. If the first line matches the second line is ignored.

To aid with platforms such as Windows, which add Unicode BOM marks to the beginning of Unicode files, the UTF-8 signature \xef\xbb\xbf will be interpreted as ‘utf-8’ encoding as well (even if no magic encoding comment is given).

If a source file uses both the UTF-8 BOM mark signature and a magic encoding comment, the only allowed encoding for the comment is ‘utf-8’. Any other encoding will cause an error.

Examples

These are some examples to clarify the different styles for defining the source code encoding at the top of a Python source file:

    With interpreter binary and using Emacs style file encoding comment:

#!/usr/bin/python # -*- coding: latin-1 -*- import os, sys . #!/usr/bin/python # -*- coding: iso-8859-15 -*- import os, sys . #!/usr/bin/python # -*- coding: ascii -*- import os, sys . 
# This Python file uses the following encoding: utf-8 import os, sys . 
#!/usr/local/bin/python # coding: latin-1 import os, sys . 
#!/usr/local/bin/python import os, sys . 
#!/usr/local/bin/python # latin-1 import os, sys . 
#!/usr/local/bin/python # # -*- coding: latin-1 -*- import os, sys . 
#!/usr/local/bin/python # -*- coding: utf-42 -*- import os, sys . 

Concepts

The PEP is based on the following concepts which would have to be implemented to enable usage of such a magic comment:

  1. The complete Python source file should use a single encoding. Embedding of differently encoded data is not allowed and will result in a decoding error during compilation of the Python source code. Any encoding which allows processing the first two lines in the way indicated above is allowed as source code encoding, this includes ASCII compatible encodings as well as certain multi-byte encodings such as Shift_JIS. It does not include encodings which use two or more bytes for all characters like e.g. UTF-16. The reason for this is to keep the encoding detection algorithm in the tokenizer simple.
  2. Handling of escape sequences should continue to work as it does now, but with all possible source code encodings, that is standard string literals (both 8-bit and Unicode) are subject to escape sequence expansion while raw string literals only expand a very small subset of escape sequences.
  3. Python’s tokenizer/compiler combo will need to be updated to work as follows:
    1. read the file
    2. decode it into Unicode assuming a fixed per-file encoding
    3. convert it into a UTF-8 byte string
    4. tokenize the UTF-8 content
    5. compile it, creating Unicode objects from the given Unicode data and creating string objects from the Unicode literal data by first reencoding the UTF-8 data into 8-bit string data using the given file encoding

    Note that Python identifiers are restricted to the ASCII subset of the encoding, and thus need no further conversion after step 4.

    Implementation

    For backwards-compatibility with existing code which currently uses non-ASCII in string literals without declaring an encoding, the implementation will be introduced in two phases:

    1. Allow non-ASCII in string literals and comments, by internally treating a missing encoding declaration as a declaration of “iso-8859-1”. This will cause arbitrary byte strings to correctly round-trip between step 2 and step 5 of the processing, and provide compatibility with Python 2.2 for Unicode literals that contain non-ASCII bytes. A warning will be issued if non-ASCII bytes are found in the input, once per improperly encoded input file.
    2. Remove the warning, and change the default encoding to “ascii”.

    The builtin compile() API will be enhanced to accept Unicode as input. 8-bit string input is subject to the standard procedure for encoding detection as described above.

    If a Unicode string with a coding declaration is passed to compile() , a SyntaxError will be raised.

    SUZUKI Hisao is working on a patch; see [2] for details. A patch implementing only phase 1 is available at [1].

    Phases

    Implementation of steps 1 and 2 above were completed in 2.3, except for changing the default encoding to “ascii”.

    The default encoding was set to “ascii” in version 2.5.

    Scope

    This PEP intends to provide an upgrade path from the current (more-or-less) undefined source code encoding situation to a more robust and portable definition.

    References

    History

    • 1.10 and above: see CVS history
    • 1.8: Added ‘.’ to the coding RE.
    • 1.7: Added warnings to phase 1 implementation. Replaced the Latin-1 default encoding with the interpreter’s default encoding. Added tweaks to compile() .
    • 1.4 — 1.6: Minor tweaks
    • 1.3: Worked in comments by Martin v. Loewis: UTF-8 BOM mark detection, Emacs style magic comment, two phase approach to the implementation

    This document has been placed in the public domain.

    Источник

Оцените статью