Julio de Leon
Julio de Leon

Reputation: 1212

How to get the data submitted using POST on Python using Pyramid?

I'm looking for the equivalent of PHP's $_POST[] in Python. On PHP, when you submit a form you can get its value by using the $_POST[]. How can I get this data on python? here is my code.

function NewUser(){
                    var firstName = $('#firstName').val();
                    var dataString = '&firstName='+firstName;
                    $.ajax({
                        type:"POST",
                        url:"newusers",
                        data:dataString,
                        dataType:'text',
                        success:function(s){
                            alert(s);
                        },
                        error:function(){
                            alert('FAILED!');
                        }


                    })
                }

This is where I throw the data.

@view_config(route_name='newusers', renderer='json')
    def newusers(self):
    return '1';

This code works fine and it returns and alert a string "1".

My question is, how can I get the submitted firstName? and put it on the return instead of "1".

Thank you in advance!

Upvotes: 2

Views: 1234

Answers (2)

Tim D
Tim D

Reputation: 690

Another variation that should work:

@view_config(route_name='newusers', renderer='json')
def newusers(self):
    # Best to check for the case of a blank/unspecified field...
    if ('firstName' in self.request.params):
        name =  str(self.request.params['firstName'])
    else:
        name = 'null'
    return name

Note: Be careful using str() function, particularly in python 2.x, as it may not be compatible with unicode input using characters beyond ascii. You might consider:

        name = (self.request.params['firstName']).encode('utf-8')

as an alternative.

Upvotes: 2

Julio de Leon
Julio de Leon

Reputation: 1212

I manage to make it work with this code.

@view_config(route_name='newusers', renderer='json')
def newusers(self):
    name =  str(self.request.POST.get('firstName'))
    return name

Upvotes: 1

Related Questions