def password_recovery_request(): """check login data and returns user data with token""" req_data = request.get_json() user_data = DB.get_object('users', req_data, create=False) if not user_data or not user_data['email']: return bad_request('Пользователь или email не зарегистрирован.\n' +\ 'The username or email address is not registered.') token = _create_token({ 'login': req_data['login'], 'type': 'passwordRecovery', 'expires': time.time() + 60 * 60 * 60}) text = """Пройдите по ссылкe, чтобы сменить пароль на ONEADIF.com: """\ + CONF.get('web', 'address')\ + '/#/passwordRecovery?token=' + token + """ Если вы не запрашивали смену пароля на ONEADIF.com, просто игнорируйте это письмо. Ссылка будет действительна в течение 1 часа. Follow this link to change your ONEADIF.com password: """ \ + CONF.get('web', 'address')\ + '/#/passwordRecovery?token=' + token + """ Ignore this message if you did not request password change Служба поддержки ONEADIF.com support""" send_email.send_email(text=text,\ fr=CONF.get('email', 'address'),\ to=user_data['email'],\ subject="ONEADIF.com - password change") return jsonify({'message':\ 'На ваш почтовый адрес было отправлено письмо с инструкциями по ' +\ 'сменен пароля.\n' +\ 'The message with password change instrunctions was sent to your ' +\ 'email address'})
def go(users): # get all plugins plugins = {} print "get all plugins..." for usr in users: for pull in users[usr]['pull']: plugins[pull] = users[usr]['push'].split(',') print "plugins: ", plugins # prepare all data pull_contents = {} print "prepare all data..." for pull, pushs in plugins.items(): pull_key = 'pull.' + pull print "pull_key: ", pull_key pull_contents[pull_key] = {} pull_class = CONF.get(pull_key, None) print "pull_class: ", pull_class if pull_class: pull_class_obj = utils.import_class(pull_class) pull_clazz = pull_class_obj() for pull_plugin_key in pull_clazz.all_keys: print "pull_plugin_key: ", pull_plugin_key pull_content = pull_clazz(pull_plugin_key) pull_contents[pull_key][pull_plugin_key] = {} pull_contents[pull_key][pull_plugin_key]['content'] = pull_content for push in pushs: if push: push_key = 'push.' + push print "push_key: ", push_key to_method = getattr(pull_content, "to_"+push) pull_contents[pull_key][pull_plugin_key][push_key] = to_method() if not pull_contents: print "get empty content." return # push all data print "push all user data..." for usr in users: print "user: "******"pull_key: ", pull_key for plugin_key in users[usr]['pull'][pull]: for push in user_push: push_key = 'push.' + push print "push_key: ", push_key push_class = CONF.get(push_key, None) print "push_class: ", push_class if push_class: push_class_obj = utils.import_class(push_class) push_clazz = push_class_obj() push_clazz(pull_contents[pull_key][plugin_key][push_key])
def get_logger(logger_name): global logger if logger == None: logger = {} if logger_name in logger: return logger.get(logger_name) if logger_name not in CONF.get('log'): raise Exception('logger_name not found') if 'file' not in CONF.get('log').get(logger_name): raise Exception('file node not found') logger[logger_name] = Log(CONF.get('log').get(logger_name).get('file')) return logger.get(logger_name)
def send_email(**email): my_address = CONF.get('email', 'address') msg = MIMEMultipart() msg.attach(MIMEText(email['text'].encode('utf-8'), 'plain', 'UTF-8')) msg['from'] = email['fr'] msg['to'] = email['to'] msg['MIME-Version'] = "1.0" msg['Subject'] = email['subject'] msg['Content-Type'] = "text/plain; charset=utf-8" msg['Content-Transfer-Encoding'] = "quoted-printable" if 'attachments' in email and email['attachments']: for item in email['attachments']: part = MIMEApplication(item['data'], Name=item['name']) part['Content-Disposition'] = 'attachment; filename="%s"' % item['name'] msg.attach(part) try: server = smtplib.SMTP_SSL(CONF.get('email', 'smtp')) server.login(CONF.get('email', 'login'), CONF.get('email', 'password')) server.sendmail(my_address, msg['to'], str(msg)) return True except Exception as exc: logging.exception('error sending email') return False
#!/usr/bin/python3 #coding=utf-8 import json from db import DBConn from conf import CONF DB = DBConn(CONF.items('db')) DB.connect() feeders_data = DB.execute(""" select id, props from devices where device_type_id = 3""") for feeder_data in feeders_data: for timer in feeder_data['props'][2]: timer.append(0) feeder_data['props'] = json.dumps(feeder_data['props']) DB.execute( """ update devices set props = %(props)s where id = %(id)s""", feeder_data)
import sys from loguru import logger from conf import CONF if len(sys.argv) != 1: CONF.load_data(sys.argv[1]) logger.warning(f"已加载配置文件 {sys.argv[1]}") else: CONF.load_data() import asyncio import datetime import random import time from concurrent.futures import ThreadPoolExecutor from typing import Dict, List from pixivpy3 import * from kf import producer, consumer, TOPIC from kafka.errors import CommitFailedError from model import * async def main(): for page in range(5): data = await loop.run_in_executor(executor, recommended_task, page) await processIllustList(data["illusts"]) # 作品放入数据库 await asyncio.sleep(1) logger.info("等待数据") while True:
from conf import CONF import importlib import sys if __name__ == "__main__": conf = None try: conf = CONF(r'./trafficgen.conf') except Exception as e: print e sys.exit(1) #Import the traffic generator #This module should implement generate function that takes the httpserver object as an argument try: generator = importlib.import_module(conf.generator) except ImportError as e: print e sys.exit(1) #Import the httpserver module #This module should implement `send` request function try: httpreq = importlib.import_module(conf.httpreq) #if conf.httpmodule == "wordpress": #from wordpressreq import WPReq as httpreq except ImportError as e: print e sys.exit(1) generator.generate(conf, httpreq)
import base64 import os from datetime import datetime, timedelta CHARS = string.ascii_letters + string.digits from hashids import Hashids sys.path.append('lenfer') from secret import get_secret, create_token from db import DBConn, splice_params from conf import CONF sys.path.append('test') DB = DBConn(CONF.items('db')) DB.verbose = True DB.connect() API_URI = 'https://dev.lenfer.ru/api/' #API_URI = 'http://my.lenfer.ru/api/' LOGGER = logging.getLogger(__name__) SECRET = get_secret(CONF.get('files', 'secret')) def _create_token(data): return create_token(data, SECRET)
import numpy as np import random import time import string import multiprocessing as mp from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import GetPosts, NewPost from wordpress_xmlrpc.methods.users import GetUserInfo from wordpress_xmlrpc.methods import media from wordpress_xmlrpc.compat import xmlrpc_client from conf import CONF import wp_posts wp_conf = None try: wp_conf = CONF(r'httpreq/wordpress/wordpress.conf') except Exception as e: print e sys.exit(1) #Choose random requests(GET or POST) based on the given GET:POST ratio def _choose_req(): s = np.random.uniform(0, 1, size=1) if s <= wp_conf.post_ratio: return "POST" elif s <= wp_conf.post_ratio + wp_conf.get_ratio: return "GET" def send(req_list):
prev_sample = samples[0] print "Dumping data starting from: ", start_timestamp, with open('raw_data.json', 'a') as outfile: for sample in samples: start_timestamp = sample.timestamp d = sample.to_dict() json.dump(d, outfile) outfile.write("\n") print "to: ", start_timestamp dump_json(cclient, start_timestamp, end_timestamp, request_limit) if __name__ == "__main__": conf = None try: conf = CONF(r'dump_ceilometer_data.conf') except Exception as e: print e sys.exit(1) if len(sys.argv) == 3: start_ts = sys.argv[1] end_ts = sys.argv[2] else: print "Incorrect args. Usage: dump_ceilometer_data.py start_timestamp end_timestamp." print "Timestamps are given in the format of: `%Y-%m-%dT%H:%M:%S.%f`" exit(1) #Connect to ceilometer, connection_pool = True for keeping the connection alive as long as the process go cclient = ceilometerclient.client.get_client( conf.c_version, os_username=conf.username,