How to validate and know if an URL is a Google Docs URL? |Python,Flask|

Viewed 760

I'm creating a website that has a function to let user share their Google Docs URL to each others. I want to validate the input of the user to be Google Docs URL before I let them post it so that it could be safe. I'm using Flask and Python and I wonder if there is anyway to validate this.

The only validations I learn so far are those from FlaskForm like below:

project_link = StringField('Google Docs link to your project', validators=[DataRequired()])

and to limits the URL's character to 100 in my models.py

I think a possible way to do it is to create some Python codes in my views.py that check if the URL contains phrases like "docs.google.com"...

I don't really know how to validate if an URL is a Google Docs URL and I would greatly appreciate it if you could show me how.

Thank you.

3 Answers

Try something like this:

url = "http://docs.google.com/an/example/google/doc"
prefixes = ["https://","http://"]

def validate(url):
    for pre in prefixes:
        url = url.strip(pre) # this gets rid of http or https prefixes
        if url.startswith("docs.google.com"):
            return True
        else:
            return False

This also has the effect of filtering out any unwanted prefixes, such as "chrome://" or "about://".

An example:

>>> url = "http://docs.google.com/document"
>>> validate(url)
True
>>> url = "https://googledocs.com"
>>> validate(url)
False
>>> url = "prefix://docs.google.com"
>>> validate(url)
False
URL='www......'
if 'docs.google.com' in URL and '&site=' not in URL:
    print(True)

As monsieuralfonse64 pointed out, you need the second half of the statement to prevent bypasses where the previous page is listed as containing docs.google.com, but not the other site.

This answer is WRONG. as was once again pointed out, any number of prefixes could be in front of a link, and anything from microsoft.com/hello?x=docs.google.com to stackoverflow.com/docs.google.com?name=hello and youtube.com/watch?v=docs.google.com would all be validated in my approach.

I would like to add one more solution to these already good solutions. For stuff like this you can always just use existing libraries!

Existing libraries probably are accounting for some corner-cases that you haven't thought of yourself (if you chose the right one). We don't want ot re-invent the wheel now, do we?

Here's how I would go about it:

from urllib.parse import urlparse

url = "https://drive.google.nl"
format = "drive.google.com"

parsed = urlparse(url)
if(parsed.netloc == format and (parsed.scheme == "http" or parsed.scheme == "https")):
    print(True)

I only tested this in python3, but I'm sure it'll also work for other python versions.

Related