Skip to content

Instantly share code, notes, and snippets.

@studentIvan
Forked from anonymous/habraproxy.py
Last active May 16, 2016 11:40
Show Gist options
  • Save studentIvan/bb1fa05f8683855cc0f98b26420a27e2 to your computer and use it in GitHub Desktop.
Save studentIvan/bb1fa05f8683855cc0f98b26420a27e2 to your computer and use it in GitHub Desktop.
.idea
*.pyc
.DS_Store

HABRAPROXY

Тестовое задание для ivelum

# coding=utf8
from flask import request, Flask, Response
from string import ascii_letters as latin
from argparse import ArgumentParser
from html2text import html2text
import webbrowser
import requests
import re
app = Flask(__name__)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--host', help=u'host на котором запускается habraproxy', default='localhost')
parser.add_argument('--port', help=u'порт на который биндится habraproxy', type=int, default=5100)
parser.add_argument('--target', help=u'цель habraproxy', default='https://habrahabr.ru')
args = parser.parse_args()
@app.errorhandler(404)
def hello(error):
"""
фронт-контроллер нашей прокси.
:param error: в нашем случае ненужная, но обязательная переменная ошибок фласка =)
:return: Response: получаем http-ответ
"""
response_html = requests.get('%s%s' % (args.target, request.path)).text
response_text = re.sub(u'[^a-zа-яё ]', '', html2text(response_html), re.UNICODE & re.IGNORECASE)
def check_word(x):
"""
функция фильтрации проверяет некую формальную целостность слов.
если слово начинается с латинской буквы то и кончаться должно ею же.
для правильной обработки "я люблю scriptи еще забываю ставить пробел".
:param x:
:return:
"""
both_latin = x[0] in latin and x[-1] in latin
both_rus = x[0] not in latin and x[-1] not in latin
return len(x) is 6 and (both_latin or both_rus)
target_words = set(filter(check_word, response_text.split()))
for word in target_words:
response_html = response_html.replace(word, u'%s™' % word)
response_html = re.sub(u'™([^\040<])', '\1', response_html)
# не вникал в тонкости кода хабра, но где-то там есть код,
# который изменяет адрес страницы на habrahabr.ru, причем делает это через раз
# поэтому ниже перехватчик таких переадресаторов =)
response_html += u'<script>window.onbeforeunload = function(e) {' \
u'window.onbeforeunload = null; var message = ' \
u'"Просто нажмите отмену.", e = e || window.event; if ' \
u'(e) {e.returnValue = message} return message}</script>'
return Response(response_html)
params = {'host': args.host, 'port': args.port}
webbrowser.open('http://{host}:{port}/'.format(**params))
app.run(**params)
flask
requests
html2text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment