text
stringlengths
0
828
# Close the file and leave the responsability to the client code to
# correctly open/close it.
os.close(tmpfd)
if '.' not in suffix:
# Just in case format is empty
return tmppath
while '.' in os.path.basename(tmppath)[:-len(suffix)]:
os.remove(tmppath)
tmpfd, tmppath = tempfile.mkstemp(
suffix=suffix,
prefix=prefix,
dir=current_app.config['CFG_TMPSHAREDDIR']
)
os.close(tmpfd)
return tmppath"
4801,"def open_url(url, headers=None):
""""""
Opens a URL. If headers are passed as argument, no check is performed and
the URL will be opened.
@param url: the URL to open
@type url: string
@param headers: the headers to use
@type headers: dictionary
@return: a file-like object as returned by urllib2.urlopen.
""""""
request = urllib2.Request(url)
if headers:
for key, value in headers.items():
request.add_header(key, value)
return URL_OPENER.open(request)"
4802,"def bulk_log(self, log_message=u""Еще одна пачка обработана"", total=None, part_log_time_minutes=5):
""""""
Возвращает инстант логгера для обработки списокв данных
:param log_message: То, что будет написано, когда время придет
:param total: Общее кол-во объектов, если вы знаете его
:param part_log_time_minutes: Раз в какое кол-во минут пытаться писать лог
:return: BulkLogger
""""""
return BulkLogger(log=self.log, log_message=log_message, total=total, part_log_time_minutes=part_log_time_minutes)"
4803,"def db(self, db_alias, shard_key=None):
""""""
Получить экземпляр работы с БД
:type db_alias: basestring Альяс БД из меты
:type shard_key: Любой тип. Некоторый идентификатор, который поможет мете найти нужную шарду. Тип зависи от принимающей стороны
:rtype: DbQueryService
""""""
if shard_key is None:
shard_key = ''
db_key = db_alias + '__' + str(shard_key)
if db_key not in self.__db_list:
self.__db_list[db_key] = DbQueryService(self, self.__default_headers, {""db_alias"": db_alias, ""dbAlias"": db_alias, ""shard_find_key"": shard_key, ""shardKey"": shard_key})
return self.__db_list[db_key]"
4804,"def __read_developer_settings(self):
""""""
Читает конфигурации разработчика с локальной машины или из переменных окружения
При этом переменная окружения приоритетнее
:return:
""""""
self.developer_settings = read_developer_settings()
if not self.developer_settings:
self.log.warning(""НЕ УСТАНОВЛЕНЫ настройки разработчика, это может приводить к проблемам в дальнейшей работе!"")"
4805,"def api_call(self, service, method, data, options):
""""""
:type app: metasdk.MetaApp
""""""
if 'self' in data:
# может не быть, если вызывается напрямую из кода,
# а не из прослоек типа DbQueryService
data.pop(""self"")
if options:
data.update(options)
_headers = dict(self.__default_headers)
if self.auth_user_id:
_headers['X-META-AuthUserID'] = str(self.auth_user_id)
request = {
""url"": self.meta_url + ""/api/v1/adptools/"" + service + ""/"" + method,
""data"": json.dumps(data),
""headers"": _headers,
""timeout"": (60, 1800)
}
for _try_idx in range(20):
try:
resp = requests.post(**request)
if resp.status_code == 200:
decoded_resp = json.loads(resp.text)
if 'data' in decoded_resp:
return decoded_resp['data'][method]
if 'error' in decoded_resp:
if 'details' in decoded_resp['error']:
eprint(decoded_resp['error']['details'])