def get(self, request): from django.views import static from django.conf import settings from base.utils import get_or_set_file, md5 param = { 'page': request.GET.get('page', ''), 'scene': request.GET.get('scene', ''), } key = md5(self.site.wxa_instance.appid + '?' + u'&'.join([u'%s=%s' % (k, v) for k, v in param.items()])) def get(): return self.site.wxa_instance.get_wxacode_unlimit(param).content filepath = get_or_set_file('%s.png' % key, get) # print filepath.replace(settings.BASE_DIR, '') document_root, path = os.path.split(filepath) res = static.serve(request, path, document_root, settings.DEBUG) if 'attname' in request.GET: res['Content-Disposition'] = 'attachment;filename="{0}"'.format( request.GET['attname']) res['Content-Type'] = 'application/octet-stream' else: res['Content-Type'] = 'image/png' res['Content-Key'] = key return res
def render_to_string(self, template_name: str, context=None, sticker=None, document=None, photo=None, keyboard=None, reply_markup=None, edit=False, **kwargs): """ На самом деле этот метод отправляет диалог. Но это имя ему задано для того чтобы IDE проверял пути к шаблонам. """ if not self.active: return False if not context: context = {} self_key = self.__class__.__name__.lower() if self_key not in context: context[self_key] = self context['emoji'] = emoji context['smile'] = smile text = self._load(template_name) version = base_utils.md5(text.encode('utf-8')) title = None m = re.search(r'title:(?P<title>.+)\n', text) if m: title = m.group('title') text = text[:m.start()] + text[m.end():] name = template_name if name.find('bot/', 0, 4) == 0: name = name[4:] if name.find('.html', -5) != -1: name = name[:-5] title_parts = name.split('/') title_associate = { 'private': 'Приватный чат', 'group': 'Групповой чат', 'errors': 'Ошибки', 'tutorial': 'Обучение', 'admin': 'Админам', } for i in range(len(title_parts)): part = title_parts[i] if part in title_associate: title_parts[i] = title_associate[part] elif i == len(title_parts) - 1 and title: title_parts[i] = title.strip() title = ' / '.join(title_parts) m = re.search(r'comment:(?P<comment>.+)\n', text) comment = '' if context and isinstance(context, dict): comment = 'context=%s' % list(context.keys()) if m: comment += '\n' + m.group('comment') text = text[:m.start()] + text[m.end():] text = text.strip() text = bot_utils.render_from_string(text, context) if sticker: self.send_sticker(sticker, **kwargs) kwargs['keyboard'] = keyboard kwargs['reply_markup'] = reply_markup if document or photo: kwargs['caption'] = text if document: return self.send_document(document, **kwargs) elif photo: return self.send_photo(photo, **kwargs) return self.send_message(text, edit=edit, **kwargs)
def do_GET(self): print('got GET to {path}'.format(path=self.path)) if 'source/js/jquery.min.js' in self.path: self.path = 'source/js/jquery.min.js' return SimpleHTTPRequestHandler.do_GET(self) if 'index' in self.path: self.get_services() return global Session session = Session() request_ip, request_port = self.request.getpeername() if '{api}/runner/command'.format(api=API_VERSION) == self.path: runner = session.query(Runner).filter_by(ip=request_ip).first() if not runner: print('<server> Не нашел runner по ip: ', request_ip) self.send_response(HTTPStatus.NOT_FOUND) self.end_headers() return # обновляем время у клиента runner.timestamp = datetime.now() session.add(runner) session.commit() self.send_response(HTTPStatus.ACCEPTED) self.end_headers() data = {'command': runner.command.name} self.wfile.write(simplejson.dumps(data).encode()) return if '{api}/service/command'.format(api=API_VERSION) == self.path: service = session.query(Service).filter_by( ip=request_ip).filter_by( dir_name=self.headers.get('dir_name')).first() if not service: print('<server> Не нашел service по ip и dir_name: ', request_ip, self.headers.get('dir_name')) self.send_response(HTTPStatus.NOT_FOUND) self.end_headers() return service.timestamp = datetime.now() session.add(service) session.commit() self.send_response(HTTPStatus.ACCEPTED) self.end_headers() data = {'command': service.command.name} if service.command.name == 'start': mode = session.query(Mode).filter_by(active=True).first() if not mode: # TODO: костыль print('Ошибка выбора активного режима') data['command'] = 'wait' self.wfile.write(simplejson.dumps(data).encode()) return default_config = session.query(DefaultConfig).filter_by( service_id=service.id).filter_by(mode_id=mode.id).first() if not default_config: # TODO: костыль print('Ошибка выбора настроек запуска, их нет(') data['command'] = 'wait' self.wfile.write(simplejson.dumps(data).encode()) return elif default_config.active: # запись параметров запуска args, conf ARG = 'arg_{index}' COMF = 'comf_{index}' data['mode'] = mode.name rows = session.query(File).filter_by( verbose_id=default_config.verbose_id).all() for row in rows: key_arg = ARG.format( index=row.index + 1) # +1 т.к. указывают индексы в конфиге с 1 data[key_arg] = row.arg key_comf = COMF.format( index=row.index + 1) # +1 т.к. в конфиге индексы с 1 data[key_comf] = row.name else: # TODO: костыль print("Ошибка, нет активных конфигов") data['command'] = 'wait' self.wfile.write(simplejson.dumps(data).encode()) return if '{api}/service/update'.format(api=API_VERSION) == self.path: service = session.query(Service).filter_by( ip=request_ip).filter_by( dir_name=self.headers.get('dir_name')).first() if not service: print('<server> Не нашел service по ip и dir_name: ', request_ip, self.headers.get('dir_name')) self.send_response(HTTPStatus.NOT_FOUND) self.end_headers() return service.timestamp = datetime.now() session.add(service) session.commit() self.send_response(HTTPStatus.ACCEPTED) self.end_headers() tmp = "/tmp" if service.defaults: dir_archiving = os.path.join(tmp, service.name) if os.path.isdir(dir_archiving): rmtree(dir_archiving) os.mkdir(dir_archiving) for config in service.defaults: mode_path = os.path.join(dir_archiving, config.mode.name) os.mkdir(mode_path) for file in config.verbose.files: if os.path.isfile(os.path.join(file.path, file.name)): copyfile(os.path.join(file.path, file.name), os.path.join(mode_path, file.name)) archive_name = make_archive(service.name, "tar", root_dir=dir_archiving) archive_path = os.path.abspath(archive_name) md5sum = utils.md5(archive_path) data_content = open(archive_path, 'rb').read() encoded_content = base64.b64encode(bytes(data_content)) data = { 'md5sum': md5sum, 'data': encoded_content, 'file_name': service.name + ".tar" } else: data = {'file': 'not_found'} # признак отсутствия файлов self.wfile.write(simplejson.dumps(data).encode()) return if '{api}/service/config'.format(api=API_VERSION) == self.path: service = session.query(Service).filter_by( ip=request_ip).filter_by( dir_name=self.headers.get('dir_name')).first() if not service: print('<server> Не нашел service по ip и dir_name: ', request_ip, self.headers.get('dir_name')) self.send_response(HTTPStatus.NOT_FOUND) self.end_headers() return service.timestamp = datetime.now() session.add(service) session.commit() self.send_response(HTTPStatus.ACCEPTED) self.end_headers() data = {'config': service.config} self.wfile.write(simplejson.dumps(data).encode())
def add(self, file_name, path): self.name = file_name self.path = path self.type = os.path.splitext(file_name)[1] self.size = os.path.getsize(os.path.join(path, file_name)) self.md5sum = md5(os.path.join(path, file_name))
def get(self, request, apiname, *k, **ks): import time from utils import Data from defs import raiseApiEx as err from defs import ApiException, CheckException self.me = None self.meid = None starttime = time.time() try: apiname = apiname.strip('/') sys_debug = self.site.setting.get('sys_debug') if sys_debug and (apiname == 'doc.html' or not apiname) and self.session_get('xme'): return self.doc(request) if not sys_debug and request.method != 'POST': err("Not Allow!") if not apiname: err("接口不能为空") apifun = None try: apifun = getattr(self, apiname) needlogin = getattr(apifun, 'logined') except: err("不存在接口 %s" % apiname) needlogin = getattr(apifun, 'logined') userrole = getattr(apifun, 'userrole') operation = getattr(apifun, 'operation') checker = getattr(apifun, 'checker') timegap = getattr(apifun, 'timegap') cachetime = getattr(apifun, 'cachetime') if timegap: from django.core.cache import cache cachekey = 'nexttime_%s_%s_%s' % ( self.get_clientkey(), self.__class__.__name__, apiname) nexttime = cache.get(cachekey) if nexttime and time.time() < nexttime: # err(u'调用太频繁:%s' % (cachekey if sys_debug else apiname)) err(u'调用太频繁') cache.set(cachekey, time.time() + timegap) if needlogin and not self.get_meid(): err(u'用户未登录', c=2001) if userrole and userrole not in self.get_roles(): err(u'用户权限不足') if operation: self.checkOperation(operation) if checker and not checker(self, request): err(u'检查不通过') kvargs = {} param = {} param.update(dict(request.GET.items())) param.update(dict(request.POST.items())) missargs = [] arginfos = getattr(apifun, 'arginfos') for p in arginfos: ap = p['info'] name = p['name'] # print name, ap.default, ap.empty, ap.hasdefault if name != '_param' and ap.empty and name not in param: param[name] = ap.default if ap.hasdefault else '' if name == '_param': kvargs[name] = param elif not ap.hasdefault and name not in param: missargs.append(name) elif not ap.hasdefault and not ap.empty and not param.get( name): missargs.append(name) else: kvargs[name] = param.get(name, ap.default) if missargs: err(u'缺失参数: %s' % (', '.join(missargs))) def doapi(): data = apifun(**kvargs) if isinstance(data, Data): data = data.data return data if cachetime: from base.utils import get_or_set_cache, md5 paramkey = u'&'.join([ u'%s=%s' % (k, v) for k, v in param.items() if not k.startswith('_') ]) apikey = 'api_cache_%s_%s' % (apiname, md5(paramkey)) def responsejson(): data = get_or_set_cache(apikey, doapi, cachetime) res = { "code": 0, "data": data } if (not data or type(data) != dict or '_msg' not in data) else { "code": 0, "msg": data['_msg'], "data": data.get('data') } res['timestamp'] = int(time.time()) return json.dumps(res, default=json_filed_default) data = HttpResponse(get_or_set_cache(apikey + '_json', responsejson, cachetime), content_type="text/json") else: data = doapi() from django.http.response import HttpResponseBase if isinstance(data, HttpResponseBase): return data res = { "code": 0, "data": data } if (not data or type(data) != dict or '_msg' not in data) else { "code": 0, "msg": data['_msg'], "data": data.get('data') } res['time'] = int((time.time() - starttime) * 1000) return self.api_response(res) except ApiException, e: res = e.args[0] if 'msg' in res: res['msg'] = self.translate(res['msg']) return self.api_response(res)
def get_clientkey(self): from base.utils import md5 key = md5( str(self.meid or self.request.session.session_key or self.get_ip())) return key