4

I have some input: '123Joe's amazing login'

What I'm looking to do with that input is remind the user that is registering to the site that he needs to make his username url friendly

So server side I would like to have some string match or comparison to see if it is indeed url friendly, and if it is okay we are golden, if not I would like to urlfy it and send it back to the user saying something like: "Hey this name: 123joes-amazing-login is better"

I'm not too sure where to start looking, any suggestions?

edit:

other io could be: "this is awesome" to "this_is_awesome" etc... just need to make sure it's url friendly!

edit 2: I wound up using this:

username = str(request.form['username'])
username = urllib.quote(username, '')
if '%' in username:

This covers the scope of the handling i.e. users can still underscore and dash.

Thanks for all the help.

Robert Hickok
  • 103
  • 1
  • 1
  • 6
  • 2
    Why not just slugify the username when it's part of a URL and leave it as-is when it's displayed on a page? For example, https://stackoverflow.com/users/22656/jon-skeet – Blender May 10 '15 at 03:54
  • I certainly could approach it in this manner. It might be a significant amount of backtracking for what I have existing. I thought of doing this is as well but would have to figure out a efficient way of going about implementing it. – Robert Hickok May 10 '15 at 04:23

2 Answers2

3

First pip install python-slugify, then

>>> import slugify
>>> username = "123Joe's amazing login"
>>> slugify.slugify(username)
'123joes-amazing-login'

You can check if the given username is equal to the slugified version, and then do your warning logic if they are unequal.

Now, I want to suggest to you that this is a questionable design choice. There is no good reason why usernames shouldn't be allowed to contain spaces and quotes. If you need them to translate into unique urls it's usually better to tackle that problem by generating a user ID aswell as the username. This can be done in such a way that it looks like a slugified version of the username, by the way (although you have to be careful about uniqueness).

wim
  • 338,267
  • 99
  • 616
  • 750
  • Ah this is wonderful! I will check it out, play with it, and report back! Also, I must admit, I do want the users to use underscores. I do allow the users to have "nice names", I'm considering to allow them to have that as a login as well. – Robert Hickok May 10 '15 at 04:14
2

It wouldn't make it safe the way you did, but you could use urllib.quote as discussed at How to percent-encode URL parameters in Python?

Community
  • 1
  • 1
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67