Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def run(options):
main_lang = config.get('database', 'language')
init = {}
for db_name in options.database_names:
init[db_name] = False
database = backend.Database(db_name)
database.connect()
if options.update:
if not database.test():
logger.info("init db")
database.init()
init[db_name] = True
elif not database.test():
raise Exception('"%s" is not a Tryton database.' % db_name)
for db_name in options.database_names:
if options.update:
with Transaction().start(db_name, 0) as transaction,\
user_id = user.id
if UserApplication.count(user_id):
logger.info('User Application has already a request: %s', login)
user_id = None
data['user'] = user_id
data.pop('key', None)
data.pop('state', None)
application, = UserApplication.create([data])
key = application.key
UserApplication.delete(UserApplication.search([
('user', '=', None),
]))
return key
elif request.method == 'DELETE':
count = LoginAttempt.count(login)
if count > config.get('session', 'max_attempt', default=5):
LoginAttempt.add(login)
abort(429)
Transaction().atexit(time.sleep, 2 ** count - 1)
applications = UserApplication.search([
('user.login', '=', login),
('key', '=', data.get('key')),
('application', '=', data.get('application')),
])
if applications:
UserApplication.delete(applications)
LoginAttempt.remove(login)
else:
LoginAttempt.add(login)
def get_config(names, section='html', default=None):
names = names[:]
while names:
value = config.get(section, '-'.join(names))
if value is not None:
return value
names = names[:-1]
return default
def wrapper(request, pool, *args, **kwargs):
nonlocal user, context
readonly_ = readonly # can not modify non local
if readonly_ is None:
if request.method in {'POST', 'PUT', 'DELETE', 'PATCH'}:
readonly_ = False
else:
readonly_ = True
if context is None:
context = {}
else:
context = context.copy()
context['_request'] = request.context
if user == 'request':
user = request.user_id
retry = config.getint('database', 'retry')
for count in range(retry, -1, -1):
if count != retry:
time.sleep(0.02 * (retry - count))
with Transaction().start(
pool.database_name, user, readonly=readonly_,
context=context) as transaction:
try:
result = func(request, pool, *args, **kwargs)
except backend.DatabaseOperationalError:
if count and not readonly_:
transaction.rollback()
continue
logger.error('%s', request, exc_info=True)
raise
except Exception:
logger.error('%s', request, exc_info=True)
app = TrytondWSGI()
if config.get('web', 'root'):
static_files = {
'/': config.get('web', 'root'),
}
app.wsgi_app = SharedDataMiddlewareIndex(
app.wsgi_app, static_files,
cache_timeout=config.getint('web', 'cache_timeout'))
num_proxies = config.getint('web', 'num_proxies')
if num_proxies:
app.wsgi_app = NumProxyFix(app.wsgi_app, num_proxies)
if config.has_section('wsgi middleware'):
for middleware in config.options('wsgi middleware'):
Middleware = resolve(config.get('wsgi middleware', middleware))
args, kwargs = (), {}
section = 'wsgi %s' % middleware
if config.has_section(section):
if config.has_option(section, 'args'):
args = eval(config.get(section, 'args'))
if config.has_option(section, 'kwargs'):
kwargs = eval(config.get(section, 'kwargs'))
app.wsgi_app = Middleware(app.wsgi_app, *args, **kwargs)
import trytond.protocols.dispatcher # noqa: E402,F401
import trytond.bus # noqa: E402,F401
from werkzeug.wrappers import Response
from werkzeug.exceptions import (
NotImplemented as NotImplementedException, BadRequest)
from trytond import backend
from trytond.wsgi import app
from trytond.transaction import Transaction
from trytond.protocols.jsonrpc import JSONEncoder, JSONDecoder
from trytond.config import config
from trytond.tools import resolve
logger = logging.getLogger(__name__)
_db_timeout = config.getint('database', 'timeout')
_cache_timeout = config.getint('bus', 'cache_timeout')
_select_timeout = config.getint('bus', 'select_timeout')
_long_polling_timeout = config.getint('bus', 'long_polling_timeout')
_allow_subscribe = config.getboolean('bus', 'allow_subscribe')
_url_host = config.get('bus', 'url_host')
_web_cache_timeout = config.getint('web', 'cache_timeout')
class _MessageQueue:
Message = collections.namedtuple('Message', 'channel content timestamp')
def __init__(self, timeout):
super().__init__()
self._lock = threading.Lock()
self._timeout = timeout
self._messages = []
def load_module_graph(graph, pool, update=None, lang=None):
# Prevent to import backend when importing module
from trytond.cache import Cache
from trytond.ir.lang import get_parent_language
if lang is None:
lang = [config.get('database', 'language')]
if update is None:
update = []
modules_todo = []
models_to_update_history = set()
# Load also parent languages
lang = set(lang)
for code in list(lang):
while code:
lang.add(code)
code = get_parent_language(code)
transaction = Transaction()
with transaction.connection.cursor() as cursor:
modules = [x.name for x in graph]
module2state = dict()
def db_list(request, *args):
if not config.getboolean('database', 'list'):
abort(HTTPStatus.FORBIDDEN)
context = {'_request': request.context}
hostname = get_hostname(request.host)
with Transaction().start(
None, 0, context=context, readonly=True, close=True,
) as transaction:
return transaction.database.list(hostname=hostname)
def start_servers(self):
ssl = config.get('ssl', 'privatekey')
# Launch Server
if config.get('jsonrpc', 'listen'):
from trytond.protocols.jsonrpc import JSONRPCDaemon
for hostname, port in parse_listen(
config.get('jsonrpc', 'listen')):
self.jsonrpcd.append(JSONRPCDaemon(hostname, port, ssl))
self.logger.info("starting JSON-RPC%s protocol on %s:%d",
ssl and ' SSL' or '', hostname or '*', port)
if config.get('xmlrpc', 'listen'):
from trytond.protocols.xmlrpc import XMLRPCDaemon
for hostname, port in parse_listen(
config.get('xmlrpc', 'listen')):
self.xmlrpcd.append(XMLRPCDaemon(hostname, port, ssl))
self.logger.info("starting XML-RPC%s protocol on %s:%d",
ssl and ' SSL' or '', hostname or '*', port)
for servers in (self.xmlrpcd, self.jsonrpcd):
for server in servers:
server.start()