1

I am receiving data into an REST API, and I want to insert it as XML code into a database. When I later read the record from the database, I expect well-formed XML code.

data=str(request.data)
cur=mydb.cursor()
currentDT = datetime.datetime.now()
val=data.replace("'","''")
cur.execute("insert into MyXMLApi(dateofInsertion,xmlData) values('%s','%s')"%(str(currentDT),val))
mydb.commit()

This is what I expect to see in the database:

"<note>
Don't forget me this weekend!
</note>"

However, this is what I actually get:

'b"<note>
Don''t forget me this weekend!
</note>"'

So I have three issues here.

  1. I have to deal with single quotes in the XML code.
  2. It should be stored as proper XML code.
  3. When I read from the database, I can't get the right code.
Ignatius
  • 2,745
  • 2
  • 20
  • 32

1 Answers1

0

request.data is a bytestring in Flask. (See property data and get_data() in the docs.) But you want to save it as non-byte, just plain string to your database. Converting with str() is not the way to do it.

Assuming you want a UTF-8 string, replace your first line with

data=request.data.decode('UTF-8')

Then you will be able to save it to your database.

About the single quotes, I don't think you should escape them yourself. Use parameter binding, and the library will do it for you.

(By the way, this sounds like a very strange use-case. Why not store data in your table as field note?)

Ignatius
  • 2,745
  • 2
  • 20
  • 32