Loading more posts...

@Jasper_Holton's profile photo

Django Template Filters to Add HTTPS and Highlight URLs You may use these Django template filters to add HTTPS to your URLs and highlight them as anchor tags (a) with simple code. I have added comments to describe how the code works.

 # app/templatetags/app_filters.py
from urlextract import URLExtract
import requests
@register.filter(name='addhttpstodomains') # The first filter, to add HTTPS
def addhttpstodomains(value):
    domains = re.findall(r'', value) # Regex to get a URL
    dic = {}
    output = ""
    for domain in domains:
        if not domain[1].lower() in escaped_domains:
            url = 'https://' + domain[1]
            if not url.lower().startswith('uglek.com'):
                    response = requests.head('https://' + domain[1]) # Get the head
                    if response.status_code == 200: # If the page exists
                        dic[domain[1]] = 'https://' + domain[1] 
                    print("URL does not exist")
                dic[domain[1]] = 'https://' + domain[1]
    replaced_items = []
    for i, j in dic.items(): # Replace without replacing twice
        if not i in replaced_items:
            value = value.replace(i, j)
    value = str(value)
    while value.find('https://') > -1: # Remove any duplicates
        value = value.replace('https://','https://')
    return value

def embedlinks(value):
    output = ""
    chunks = value.split("https://") # Split at HTTPS
    for x, chunk in enumerate(chunks): # Enumerate over split sections
        if x != 0:
            chunk = "https://" + chunk # Add HTTPS back in
        urls = extractor.find_urls(chunk); # Find URL in chunk
        dic = {}
        for url in urls:
            plus = ' (it\'s on Uglek)' # Configure anchor tag
            if not url[8:17].lower() == 'uglek.com':
                plus = ' (it will take you outside of Uglek)'
            if url.endswith('.') or url.endswith(','):
                url = url[:-1]
            if not url.lower().startswith('uglek.com') and url.lower().startswith('https://'):
                    response = requests.head(url) # Get the page
                    if response.status_code == 200: # If it exists
                        dic[url] = '' + url[8:] + '' # Build anchor tag to replace URL with
                    print("URL does not exist")
            elif url.startswith('https://'):
                dic[url] = '' + url[8:] + ''
        for i, j in dic.items(): # Find and replace in chunk
            chunk = chunk.replace(i, j)
        output = output + chunk # Put the pieces back together
    return output
In action, these tags look like:
{{ post.content|addhttpstodomains|embedlinks }} # Add HTTPS and embed links

@Jasper_Holton's profile photo

How to Upgrade Python Googletrans to Google Translate Enterprise API Upgrading to Google Translate Enterprise is fairly simple. It only involves modifying the initialization of the translator and changing the translate command. This looks like the following:

# app/templatetags/app_filters.py
from google.cloud import translate_v2 as translate
# translator = translate.Translator() -- Remove this
translator = translate.Client.from_service_account_json('/home/path/to/service-account-file.json') # Change to this
And update the individual translate lines in each translation template filter

# app/templatetags/app_filters.py
# translation = translator.translate(...) -- Remove this
translation = translator.translate(value, target_language=lang, source_language='en', format_='html')['translatedText'] # Change to this
This is all it takes to get the Django template tags from my previous translation example working with Google Cloud Enterprise translation. Visit the previous example: uglek.com/post/300/ or see the code in action by using the "Language" button at the top of the site or sidebar (bottom on mobile) and selecting a language to translate the website.

one comment.

Jasper_Holton's profile photo

Uglek is now mostly translated, save for a few views. It is also much faster with this translation API.

Loading more posts...

© Uglek, 2022

Terms of Use and Privacy Policy