JoeTilsed
JoeTilsed

Reputation: 111

how to check if an input is either a string or unicode in python

How do I check if someones input is either a string or unicode in my python API program:

# POST: Add new item to data
# E.G. '{"title":"Read a book", "description":"Reading..."}'
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
    def create_task():
        if not request.json or not 'title' in request.json:
            abort(400)
        if 'title' in request.json and type(request.json['title']) != str:
            abort(400)
        if 'description' in request.json and type(request.json['description']) is not str:
            abort(400)
       task = {
            'id': tasks[-1]['id'] + 1,
            'title': request.json['title'],
            'description': request.json.get('description', ""),
            'done': False
        }
        tasks.append(task)
        return jsonify({'task': [make_public_task(task)]}), 201

the code that will have to change will need to be this bit:

if 'title' in request.json and type(request.json['title']) != str:

and

if 'description' in request.json and type(request.json['description']) is not str:

I tried

not in [str, unicode]:

but that didn't work.

Any ideas? Many thanks in advance.

Upvotes: 1

Views: 1461

Answers (2)

Kos
Kos

Reputation: 72241

How do I check if someones input is either a string or unicode in my python API program:

No need to check

You're writing in Python 3, so there's no such distinction in the first place - unicode no longer exists. You only have one kind of strings (str) and you have byte buffers (bytes) and for your problem bytes are not even relevant.

Looks like you're using Flask? Flask internally takes care of decoding network requests. By the time you asked about request.json, Flask already internally decoded the request with appropriate encoding and gave you a nice representation:

  • json objects are of type dict
  • json arrays are of type list
  • json strings are of type str (I repeat - already decoded for you)
  • json numbers are of type int
  • json nulls are None

See? No bytes, don't worry about it now. You'll need to worry about bytes when dealing with raw data like file contents.

Upvotes: 0

Ján Janech
Ján Janech

Reputation: 13

You can check it as follows:

if isintance(request.json.get('title'), basestring):
    ...

basestring is common ancestor for str and ucicode in Python 2.7. By using get instead of [] operator you can even get rid of 'title' in request.json check

Upvotes: 1

Related Questions