Properly encoding a URL to be assigned to a link.url

Hi all!

I’m looking to add a query string to the end of a URL with the possibility of special characters that need to be encoded before assigning to a link.url.

I tried importing urllib and urllib2 but they’re not currently implemented. I’ve done some Googling but maybe I missed something or wasn’t searching for the right thing. :confused:

Any idea how I might take "http://www.google.com/search?q=Meat & Potatoes", and encode it to a proper URL like "http://www.google.com/search?q=Meat+%3F+Potatoes" ?

Thanks in advance!

Hi there,

urllib3 is implemented (listed here : https://anvil.works/doc/index.html#-div-id-python_packages-python-packages-div-).

I’m about to try it myself and will edit this post accordingly…

EDIT -
Tested in Python 3.6 Only

I can get it working server side but not client side (yet). In a server module do this :

import anvil.server
import urllib.parse

@anvil.server.callable
def urlencode(s):
  return urllib.parse.quote_plus(s)

Then in your form do this :

encoded_string = anvil.server.call('urlencode',<unencoded string>)

To avoid encoding the whole string, you could do this :

return urllib.parse.quote_plus(s,safe="/:")

The “safe” parameter indicates characters to ignore during encoding.

1 Like

Hi there,

As David says, you can use urllib on the server. On the client or server, you can use anvil.http.url_encode().

(anvil.http.url_encode() and url_decode() are new. Previously there was an undocumented client-side-only function called anvil.http.encode_uri_component() - this will still work, but it’s deprecated.)

5 Likes

Thank you David & Meredydd!

I missed the python module portion of the documentation. That just opened up a whole new world!

Cheers!

1 Like