1

我试图将 unicode 数据保存到外部 web 服务。

当我尝试保存æ-ø-å时,它会保存为æ-ø-Ã¥外部系统。

编辑:

(我的名字值是Jørn)(来自 django 的值J\\xf8rn

firstname.value=user_firstname=Jørn

如果我尝试使用编码,这是我的结果:

firstname.value=user_firstname.encode('ascii', 'replace')=J?rn

firstname.value=user_firstname.encode('ascii', 'xmlcharrefreplace')=Jørn

firstname.value=user_firstname.encode('ascii', 'backslashreplace')=J\xf8rn

firstname.value=user_firstname.encode('ascii', 'ignore')= 我使用忽略得到一个 unicode 错误。

我更新用户的表单:

def show_userform(request):
    if request.method == 'POST':
        
        form = UserForm(request.POST, request.user)

        
        if form.is_valid():
            u = UserProfile.objects.get(username = request.user)

            
            firstname = form.cleaned_data['first_name']
            lastname = form.cleaned_data['last_name']
            
            tasks.update_webservice.delay(user_firstname=firstname, user_lastname=lastname)
            

            return HttpResponseRedirect('/thank-you/')

    else:
        form = UserForm(instance=request.user) # An unbound form

    return render(request, 'myapp/form.html', {
        'form': form,
    })

这是我的任务:

from suds.client import Client

@task()
def update_webservice(user_firstname, user_lastname):

    membermap = client.factory.create('ns2:Map')

    firstname = client.factory.create('ns2:mapItem')
    firstname.key="Firstname"
    firstname.value=user_firstname

    lastname = client.factory.create('ns2:mapItem')
    lastname.key="Lastname"
    lastname.value=user_lastname


    membermap.item.append(firstname)
    membermap.item.append(lastname)


    d = dict(CustomerId='xxx', Password='xxx', PersonId='xxx', ContactData=membermap)


    try:
        #Send updates to SetPerson function
        result = client.service.SetPerson(**d)
    except WebFault, e:
        print e  

我需要做什么才能正确保存数据?

4

2 回答 2

0

Your external system is interpreting your UTF-8 as if it were Latin-1, or maybe Windows-1252. That's bad.

Encoding or decoding ASCII is not going to help. Your string is definitely not plain ASCII.

If you're lucky, it's just that you're missing some option in that web service's API, with which you could tell it that you're sending it UTF-8.

If not, you've got quite a maintenance headache on your hands, but you can still fix what you get back. The web service took the string you encoded as UTF-8 and decoded it as Latin-1, so you just need to do the exact reverse of that:

user_firstname = user_firstname.encode('latin-1').decode('utf-8')
于 2013-08-28T06:07:59.097 回答
-1

类型的用途decodeencode方法str。例如 :

x = "this is a test" # ascii encode 
x = x.encode("utf-8") # utf-8 encoded
x = x.decode("utf-8") # ascii encoded
于 2013-07-15T09:47:20.200 回答