IOS, Json, Web2py.

360 views
Skip to first unread message

Mchurch

unread,
Oct 23, 2012, 4:23:16 AM10/23/12
to web...@googlegroups.com
Dear all, I'm trying to send json data from an IOS device to web2py server.
I can already receive Json-data from web2py server on my Iphone, but I'm not able to send it back again!
From ios device I'm using Afnetworking framework, but even if i use something else the error i got is always the same:
{NSErrorFailingURLKey=http://127.0.0.1:8000/Json/default/ricevo, NSLocalizedDescription=Expected status code in (200-299), got 500

I think the problem is with my function "ricevo", what exactly i should put in my action to receive my Json data? 
I've tried many solutions, but with no result.
Can You point me in the right direction?
Thanks guys.
Marco
def ricevo():
  import gluon.contrib.simplejson as sj 
  data=sj.loads(request.body.read()) 
  return()

def ricevo():
    from json import loads, dumps
    data =  loads(request.vars.myvar)
    return dumps(data)

Niphlod

unread,
Oct 23, 2012, 4:31:36 AM10/23/12
to web...@googlegroups.com
in what format are you posting json back to the server (not the format of the json, that is of course json ... just the way you use to transmit data) ? are you using application/x-www-form-urlencoded ? multipart/form-data ? binary post ?

Mchurch

unread,
Oct 23, 2012, 4:50:22 AM10/23/12
to web...@googlegroups.com
I followed instructons,
If you're using AFHTTPClient, set the parameterEncoding property to AFJSONParameterEncoding. Any method on that HTTP client with aparameters argument will now encode the passed object into a JSON string and set the HTTP body and Content-Type header appropriately.

Thanks Niphlod 

Niphlod

unread,
Oct 23, 2012, 5:55:36 AM10/23/12
to
that's the problem when you don't know what something does.....

try to print out request.vars and request.vars.body.read() and see their contents.

PS: you can also watch the errors for the app to investigate the issue (if your phone is getting a 500, it's probable that the error is logged in web2py)

Mchurch

unread,
Oct 23, 2012, 9:27:46 AM10/23/12
to web...@googlegroups.com
from the app, no more errors, always that "500".
try to print out request.vars and request.vars.body.read() and see their contents.

I have to think and study  more about that; it's a json call, i can't reach directly that page, i should give the server response back to the app to check what web2py reads.
But from IOS i don't know (yet) how to do!
Thanks Niphlod.

Niphlod

unread,
Oct 23, 2012, 9:30:42 AM10/23/12
to web...@googlegroups.com
What I said was that if you print on the server-side you can see what happens on the "endpoint" you have control of: not IOS, the webserver!

Mchurch

unread,
Oct 23, 2012, 9:38:26 AM10/23/12
to web...@googlegroups.com
but i don't open that page in a browser, i'm just sending data.
Should I use  a console error like firebug may be?
Sorry for the stupid question, but if i open the page in a browser without the data from ios i get from web2py "Expected string o JSON...". 
I'm lost somewhere between IOs and web2py!!! Be patient Niphlod...
:)

Niphlod

unread,
Oct 23, 2012, 11:10:34 AM10/23/12
to web...@googlegroups.com
if you PRINT something, you don't return something to the device, but you can see the something on the console, .i.e. the shell where you started web2py.py . I'm guessing that at least you have access to your developing environment :P !

Mchurch

unread,
Oct 23, 2012, 11:44:45 AM10/23/12
to web...@googlegroups.com
I'll try, thanks.
Ps. Did You eat some snakes for breakfast?....
:)

Niphlod

unread,
Oct 23, 2012, 11:55:34 AM10/23/12
to web...@googlegroups.com
almost dinner time here.... :P

Mchurch

unread,
Oct 24, 2012, 3:01:40 AM10/24/12
to web...@googlegroups.com
Hi Niphlod, did You hope to be free of me so soon? :)
Looking at web2py errors, if i make a post request values are empty (not if i make a GET, but the final result is the same).
Using "CHARLES, web debugging proxy" i can see that data are dispatched with correct values and correct Content-Type (application/Json).
Im doing my best....





POST /Json/default/ricevo HTTP/1.1
Host 127.0.0.1:8000
Accept */*
Accept-Encoding gzip
Content-Length 36
Accept-Language en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8
Content-Type application/json; charset=utf-8
Connection keep-alive
User-Agent mirko.json/1.0 (unknown, iPhone OS 6.0, iPhone Simulator, Scale/1.000000)
 

<type 'exceptions.TypeError'>(expected string or buffer)

inspect attributes



  • Function argument list
    (self=<json.decoder.JSONDecoder object>, s=<Storage {}>, _w=<built-in method match of _sre.SRE_Pattern object>)

    Code listing

    Variables

Context

locals

 

request

 

session

 

response

locals

s

:

<Storage {}>

self

:

<json.decoder.JSONDecoder object>

request

ajax

:

False

application

:

Json

args

:


body

:

<open file '<fdopen>', mode 'w+b' at 0x11c143c00>

client

:

127.0.0.1

controller

:

default

cookies

:


env

:

app_folders

:

set(['/Users/marcoMchurch/Sites/web2py/applications/Json/', '/Users/marcoMchurch/Sites/web2py/applications/welcome/', '/Users/marcoMchurch/Sites/web2py/applications/admin/'])

applications_parent

:

/.…../web2py

cmd_args

:


cmd_options

:

<Values at 0x1104a53f8: {'verbose': False, 'ip': '127.0.0.1', 'shutdown_timeout': 5, 'taskbar': False, 'nocron': False, 'pid_filename': 'httpserver.pid', 'maxthreads': None, 'softcron': False, 'server_name': 'marcos-', 'bpython': False, 'nogui': False, 'port': 8000, 'extcron': False, 'debuglevel': 30, 'test': None, 'folder': '/Users/marcoMchurch/Sites/web2py', 'config': '', 'import_models': False, 'winservice': '', 'shell': None, 'run': '', 'log_filename': 'httpserver.log', 'args': [''], 'socket_timeout': 1, 'ssl_ca_certificate': None, 'scheduler': None, 'profiler_filename': None, 'ssl_private_key': '', 'password': '<ask>', 'request_queue_size': 5, 'ssl_certificate': '', 'cronjob': False, 'numthreads': None, 'quiet': False, 'interfaces': None, 'minthreads': None, 'timeout': 10, 'plain': False, 'nobanner': False}>

content_length

:

36

content_type

:

application/json; charset=utf-8

db_sessions

:

set([])

debugging

:

False

gluon_parent

:

….web2py

http_accept

:

*/*

http_accept_encoding

:

gzip

http_accept_language

:

en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8

http_connection

:

keep-alive

http_content_length

:

36

http_content_type

:

application/json; charset=utf-8

http_host

:

127.0.0.1:8000

http_user_agent

:

mirko.json/1.0 (unknown, iPhone OS 6.0, iPhone Simulator, Scale/1.000000)

is_jython

:

False

is_pypy

:

False

path_info

:

/Json/default/ricevo

query_string

:


remote_addr

:

127.0.0.1

remote_port

:

60150

request_method

:

POST

script_name

:


server_name

:

marcos-……

server_port

:

8000

server_protocol

:

HTTP/1.1

server_software

:

Rocket 1.2.4

web2py_crontype

:

hard

web2py_path

:

/Users/marcoMchurch/Sites/web2py

web2py_version

:

1

99

4

datetime.datetime(2011, 12, 14, 14, 46, 14)

stable

wsgi_errors

:

<open file '<stderr>', mode 'w' at 0x10f7b2270>

wsgi_file_wrapper

:

<class wsgiref.util.FileWrapper at 0x1103c1328>

wsgi_input

:

<socket._fileobject object at 0x117971950>

wsgi_multiprocess

:

False

wsgi_multithread

:

True

wsgi_run_once

:

False

wsgi_url_scheme

:

http

wsgi_version

:

1

0

extension

:

html

folder

:

/Users/marcoMchurch/Sites/web2py/applications/Json/

function

:

ricevo

get_vars

:


global_settings

:

app_folders

:

set(['/Users/marcoMchurch/Sites/web2py/applications/Json/', '/Users/marcoMchurch/Sites/web2py/applications/welcome/', '/Users/marcoMchurch/Sites/web2py/applications/admin/'])

applications_parent

:

/Users/marcoMchurch/Sites/web2py

cmd_args

:


cmd_options

:

<Values at 0x1104a53f8: {'verbose': False, 'ip': '127.0.0.1', 'shutdown_timeout': 5, 'taskbar': False, 'nocron': False, 'pid_filename': 'httpserver.pid', 'maxthreads': None, 'softcron': False, 'server_name': 'marcos-imac.homenet.telecomitalia.it', 'bpython': False, 'nogui': False, 'port': 8000, 'extcron': False, 'debuglevel': 30, 'test': None, 'folder': '/Users/marcoMchurch/Sites/web2py', 'config': '', 'import_models': False, 'winservice': '', 'shell': None, 'run': '', 'log_filename': 'httpserver.log', 'args': [''], 'socket_timeout': 1, 'ssl_ca_certificate': None, 'scheduler': None, 'profiler_filename': None, 'ssl_private_key': '', 'password': '<ask>', 'request_queue_size': 5, 'ssl_certificate': '', 'cronjob': False, 'numthreads': None, 'quiet': False, 'interfaces': None, 'minthreads': None, 'timeout': 10, 'plain': False, 'nobanner': False}>

db_sessions

:

set([])

debugging

:

False

gluon_parent

:

/Users/marcoMchurch/Sites/web2py

is_jython

:

False

is_pypy

:

False

web2py_crontype

:

hard

web2py_version

:

1

99

4

datetime.datetime(2011, 12, 14, 14, 46, 14)

stable

is_https

:

False

is_local

:

True

is_restful

:

False

now

:

datetime.datetime(2012, 10, 23, 23, 37, 12, 447022)

post_vars

:


url

:

/Json/default/ricevo

utcnow

:

datetime.datetime(2012, 10, 23, 21, 37, 12, 447035)

uuid

:

Json/127.0.0.1.2012-10-23.23-37-12.35f491ef-469f-421f-93e9-0cebff13da2f

vars

:


wsgi

:

environ

:

CONTENT_LENGTH

:

36

CONTENT_TYPE

:

application/json; charset=utf-8

HTTP_ACCEPT

:

*/*

HTTP_ACCEPT_ENCODING

:

gzip

HTTP_ACCEPT_LANGUAGE

:

en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8

HTTP_CONNECTION

:

keep-alive

HTTP_CONTENT_LENGTH

:

36

HTTP_CONTENT_TYPE

:

application/json; charset=utf-8

HTTP_HOST

:

127.0.0.1:8000

HTTP_USER_AGENT

:

mirko.json/1.0 (unknown, iPhone OS 6.0, iPhone Simulator, Scale/1.000000)

PATH_INFO

:

/Json/default/ricevo

QUERY_STRING

:


REMOTE_ADDR

:

127.0.0.1

REMOTE_PORT

:

60150

REQUEST_METHOD

:

POST

SCRIPT_NAME

:


SERVER_NAME

:

marcos-……

SERVER_PORT

:

8000

SERVER_PROTOCOL

:

HTTP/1.1

SERVER_SOFTWARE

:

Rocket 1.2.4

wsgi.errors

:

<open file '<stderr>', mode 'w' at 0x10f7b2270>

wsgi.file_wrapper

:

<class wsgiref.util.FileWrapper at 0x1103c1328>

wsgi.input

:

<open file '<fdopen>', mode 'w+b' at 0x11c143c00>

wsgi.multiprocess

:

False

wsgi.multithread

:

True

wsgi.run_once

:

False

wsgi.url_scheme

:

http

wsgi.version

:

1

IN FILE: /USERS/MARCOMchurch/SITES/WEB2PY/APPLICATIONS/JSON/CONTROLLERS/DEFAULT.PY

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.


# -*- coding: utf-8 -*-

# this file is released under public domain and you can use without limitations


#########################################################################

## This is a samples controller

## - index is the default action of any application

## - user is required for authentication and authorization

## - download is for downloading files uploaded in the db (does streaming)

## - call exposes all registered services (none by default)

#########################################################################

……

def ricevo():

    from json import loads, dumps

    data loads(request.vars)

    print data

    print request.vars.body.read()

    print request.vars

    return dumps(data)

Mchurch

unread,
Oct 24, 2012, 3:22:13 AM10/24/12
to web...@googlegroups.com
import gluon.contrib.simplejson
    data = gluon.contrib.simplejson.loads(request.body.read())

That was the trick....
Thank You  Niphlod, You put me in the right direction.
IOS + WEB2PY = beautiful combination!!
Mchurch

Niphlod

unread,
Oct 24, 2012, 5:23:08 AM10/24/12
to web...@googlegroups.com
For future users reading this thread... this means that the Iphone sent the JSON object POSTing to the page directly in the data stream, without "the usual" form encoding. For that, you can access what has been posted "in raw format" with request.body.read().

PS: Keep the code small

import gluon.contrib.simplejson as sj  #just if you don't have simplejson in python path
#in that case "import simplejson as sj" works
data
= sj.loads(request.body.read())

Philipp Müller

unread,
Jun 10, 2013, 4:58:16 PM6/10/13
to web...@googlegroups.com
So far, this seems to work fine. I struggle though when trying to write this data in my database.

I tried doing:
data = sj.loads(request.body.read())
#and later
return dict(db.someDatabase.insert(data))
#or
return dict(db.someDatabase.validate_and_insert(data))

for all of which I got the error message:

insert() takes exactly 1 argument (2 given)


Any ideas on how to solve this would be highly appreciated.

Regards,
Philipp

Massimo Di Pierro

unread,
Jun 10, 2013, 5:02:36 PM6/10/13
to web...@googlegroups.com
return dict(db.someDatabase.insert(**data))
#or
return dict(db.someDatabase.validate_and_insert(**data))

Niphlod

unread,
Jun 10, 2013, 5:14:42 PM6/10/13
to web...@googlegroups.com
ps: recent web2py releases should parse application/json POSTs transparently, no need to request.body.read() anymore.... it goes all in request.vars and request.post_vars as usual.

Philipp Müller

unread,
Jun 10, 2013, 5:15:51 PM6/10/13
to web...@googlegroups.com
Thanks so much. This works for
dict(db.someTable.validate_and_insert(**data))
but for some reason not for
dict(db.someTable.insert(**data))

That's fine for me, I'm just wondering though.
Btw: What exactly does ** do in this case?

Thanks again and regards,
Philipp

Massimo Di Pierro

unread,
Jun 10, 2013, 10:23:16 PM6/10/13
to web...@googlegroups.com
welll... this should work:

   db.someTable.insert(**data)

but insert returns a number (actually a Reference object) and therefore you cannot pass it to a dict as in:

   dict(db.someTable.insert(**data))

Insert and validate returns a dict instead (containing the id and errors)

Ray (a.k.a. Iceberg)

unread,
Jul 25, 2013, 12:45:58 PM7/25/13
to web...@googlegroups.com


On Tuesday, June 11, 2013 5:14:42 AM UTC+8, Niphlod wrote:
ps: recent web2py releases should parse application/json POSTs transparently, no need to request.body.read() anymore.... it goes all in request.vars and request.post_vars as usual.


Sorry to chime in an old thread, but which "recent version" of web2py supports application/json in, oops, POST? Is there any chance that web2py also support request Content-Type=application/json in PUT?

Ray (a.k.a. Iceberg)

unread,
Jul 25, 2013, 1:10:51 PM7/25/13
to web...@googlegroups.com

Forget previous post please. I just tried and found out http PUT is also supported in latest web2py 2.5.1
Reply all
Reply to author
Forward
0 new messages