# -*- coding:utf-8 -*-
# @Time    : 2018/10/10 14:53
# @Author  : Brady
# @File    : toolkit.py
# @Software: PyCharm
# @Contact : bradychen1024@gmail.com

import pymongo


class MongoDbClient:
    """
    mongodb的Client上下文管理器
    with MongoDbClient('collection') as mongo:
        mongo.xxx()
    """

    def __init__(self, collection, db):
        self.host = '121.9.245.183'
        self.port = 27017
        self.db_name = db
        self.user = 'zane'
        self.pwd = '*#06#'
        self.collection = collection
        self.client = pymongo.MongoClient(
            host=self.host,
            username=self.user,
            password=self.pwd,
            port=self.port
        )

    def __enter__(self):
        return self.client[self.db_name][self.collection]

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()

def format_headers(string)->dict:
    """
    将在Chrome上复制下来的浏览器UA格式化成字典，以\n为切割点
    :param string: 使用三引号的字符串
    :return:
    """
    string = string.strip().replace(' ', '').split('\n')
    dict_ua = {}
    for key_value in string:
        dict_ua.update({key_value.split(':')[0]: key_value.split(':')[1]})
    return dict_ua