Skip to content

Instantly share code, notes, and snippets.

@halicki
Last active March 15, 2018 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halicki/2bda98865f8ffcaecedcb84bc0e70a44 to your computer and use it in GitHub Desktop.
Save halicki/2bda98865f8ffcaecedcb84bc0e70a44 to your computer and use it in GitHub Desktop.
Python Level UP 2018 - Podsumowanie pracy domowej

Podsumowanie pracy domowej nr 1

  • Głowny cel: deploy na Heroku, 115 osobom się udało! 🍺
  • Część prac zwracała kompletne strony www Respect! Ale trudno było sprawdzać.

/

Zwracanie Hello, World!

  • Sprawdzarka reagowała tylko na response == 'Hello, World!' sorry.

/now

Zwracanie czasu UTC.

  • Przykład:

    from datetime import datetime
    
    @app.route('/now')
    def time():
        now = datetime.utcnow()
        return now.strftime("%Y-%m-%d %H:%M:%S.%f")
  • Kolejny, może fajniejszy:

    from datetime import datetime
    
    def foo():
        return datetime.utcnow()
  • Ciekawostka: Lokalizacja serwerów a now().

    Jaka jest różnica czasu zwracanego dla now() odpalonego w USA i Europie?

/user-agent

Format zwracany: {device-type} / {os} / {browser}

from flask import request
from user_agents import parse


@app.route('/user-agent')
def agent():   

    return str(parse(request.user_agent))

Inny sposób na zdobycie header`a (IMHO mniej optymalny):

  • request.headers.get('User-Agent')

/counter

Proste/naiwne zliczanie odwiedzin.

count = 0

@app.route('/counter')
def counter():
    global count
    count += 1
    return str(count) 

Jaki był problem? Ilość workerów > 1 (źródło: worker-processes)

Standardowe środowisko uruchomieniowe heroku ma więcej niż jeden worker.

~/Projects/level-up/homework-01
$ heroku run env | grep WEB_CONCURRENCY
WEB_CONCURRENCY=2

Pomysły na rozwiązanie?

  • ograniczenie liczby workerów:

    heroku config:set WEB_CONCURRENCY=1
  • multiprocessing

    from multiprocessing import Value
    
    counter = Value(...)
    
        ...
        with counter.get_lock():
                counter.value += 1
        ...
  • synchronizacja na plikach? Czy działa?

    @app.route('/counter')
    def visitcount():
        with open("visitors.txt", "r+") as f:
            fileContent = f.read()
    
            if fileContent == "":
                count = 1
            else:
                count = int(fileContent) + 1
            
            f.seek(0)
            f.write(str(count))
            f.truncate()
            
            return str(count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment