0

I'm translating PHP code to Python code which inserts data into a MySql table.

There are four possible columns based on a naming convention: image_ + [hq,sq, lq, thumb] + _url

The php code is as follows (using Laravel DB Query):

DB::table('items')
                ->insertGetId(array(
                   'title' => $title,
                    'image_' . $quality . '_url' => $amazon_url,
                ));

The corresponding python code (using SqlAlchemy Core) which is giving me a syntax error:

item_ins = items_tbl.insert().values(title=item_title, 
                                                   image_+quality+_url=amazon_url

            )

How can I accomplish the same result in Python without reverting to if/else statements?

1 Answer 1

1

You can't have variably named keyword arguments in a Python function call. However, you can expand a dict into keyword arguments:

item_ins = items_tbl.insert().values(**{'title' : item_title,
                                        'image_'+quality+'_url' : amazon_url})

If quality=='hq' for example, this is equivalent to calling

item_ins = items_tbl.insert().values(title = item_title,
                                     image_hq_url: amazon_url)

You should also note that in the syntax you tried to use, you tried to treat image_ and _url as string literals and quality as a variable, without making any syntactic distinction between them. There's no way that would work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.