本文整理汇总了Python中secrets.token_urlsafe方法的典型用法代码示例。如果您正苦于以下问题:Python secrets.token_urlsafe方法的具体用法?Python secrets.token_urlsafe怎么用?Python secrets.token_urlsafe使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类secrets
的用法示例。
在下文中一共展示了secrets.token_urlsafe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_app
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def write_app(filename, **runargs):
text = secrets.token_urlsafe()
with open(filename, "w") as f:
f.write(
dedent(
f"""\
import os
from sanic import Sanic
app = Sanic(__name__)
@app.listener("after_server_start")
def complete(*args):
print("complete", os.getpid(), {text!r})
if __name__ == "__main__":
app.run(**{runargs!r})
"""
)
)
return text
示例2: qute_settings
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def qute_settings(url: QUrl) -> _HandlerRet:
"""Handler for qute://settings. View/change qute configuration."""
global csrf_token
if url.path() == '/set':
if url.password() != csrf_token:
message.error("Invalid CSRF token for qute://settings!")
raise RequestDeniedError("Invalid CSRF token!")
return _qute_settings_set(url)
# Requests to qute://settings/set should only be allowed from
# qute://settings. As an additional security precaution, we generate a CSRF
# token to use here.
if secrets:
csrf_token = secrets.token_urlsafe()
else:
# On Python < 3.6, from secrets.py
token = base64.urlsafe_b64encode(os.urandom(32))
csrf_token = token.rstrip(b'=').decode('ascii')
src = jinja.render('settings.html', title='settings',
configdata=configdata,
confget=config.instance.get_str,
csrf_token=csrf_token)
return 'text/html', src
示例3: add_slack_btn
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def add_slack_btn(request, code):
project = _get_project_for_user(request, code)
state = token_urlsafe()
authorize_url = "https://slack.com/oauth/v2/authorize?" + urlencode(
{
"scope": "incoming-webhook",
"client_id": settings.SLACK_CLIENT_ID,
"state": state,
}
)
ctx = {
"project": project,
"page": "channels",
"authorize_url": authorize_url,
}
request.session["add_slack"] = (state, str(project.code))
return render(request, "integrations/add_slack_btn.html", ctx)
示例4: add_pushbullet
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def add_pushbullet(request, code):
project = _get_project_for_user(request, code)
redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet-complete")
state = token_urlsafe()
authorize_url = "https://www.pushbullet.com/authorize?" + urlencode(
{
"client_id": settings.PUSHBULLET_CLIENT_ID,
"redirect_uri": redirect_uri,
"response_type": "code",
"state": state,
}
)
ctx = {
"page": "channels",
"project": project,
"authorize_url": authorize_url,
}
request.session["add_pushbullet"] = (state, str(project.code))
return render(request, "integrations/add_pushbullet.html", ctx)
示例5: _500
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def _500(request, exception):
error_id = secrets.token_urlsafe(32)
if exception.__class__ is UserException:
debug("User exception: %s" % exception.message, exc_info=True)
message = exception.message
elif exception.__class__ is json.JSONDecodeError:
debug(ERROR_INVALID_JSON, exc_info=True,error_id=error_id)
message = ERROR_INVALID_JSON
elif exception.__class__ is InvalidUsage :
debug(ERROR_INVALID_USAGE, exc_info=True)
message = ERROR_INVALID_USAGE
else:
warning("Exception in API", exc_info=True)
message = ERROR_TEXT
return jsonify({'success': False, 'result': {'message': message,'errorId':error_id}},
status=500, headers=generate_cors_headers(request))
示例6: cmd_web_access
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def cmd_web_access(bot, user, text, command, parameter):
auth_method = var.config.get("webinterface", "auth_method")
if auth_method == 'token':
interface.banned_ip = []
interface.bad_access_count = {}
user_info = var.db.get("user", user, fallback='{}')
user_dict = json.loads(user_info)
if 'token' in user_dict:
var.db.remove_option("web_token", user_dict['token'])
token = secrets.token_urlsafe(5)
user_dict['token'] = token
user_dict['token_created'] = str(datetime.datetime.now())
user_dict['last_ip'] = ''
var.db.set("web_token", token, user)
var.db.set("user", user, json.dumps(user_dict))
access_address = var.config.get("webinterface", "access_address") + "/?token=" + token
else:
access_address = var.config.get("webinterface", "access_address")
bot.send_msg(constants.strings('webpage_address', address=access_address), text)
示例7: init_config
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def init_config():
''' If local.ini does not exist, then create it. '''
local_ini_path = get_path('conf/local.ini')
if not local_ini_path.exists():
logger.info('Creating conf/local.ini')
template_path = get_path('conf/local.ini.template')
shutil.copyfile(template_path, local_ini_path)
config = configparser.ConfigParser()
config.optionxform = str
config.read([local_ini_path])
config['database']['host'] = 'db'
config['database']['db'] = 'starbelly'
config['database']['user'] = 'starbelly-app'
config['database']['password'] = secrets.token_urlsafe(nbytes=15)
config['database']['super_user'] = 'admin'
config['database']['super_password'] = secrets.token_urlsafe(nbytes=15)
with open(local_ini_path, 'w') as local_ini:
config.write(local_ini)
示例8: duplicate_into_same_workflow
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def duplicate_into_same_workflow(self, to_tab):
# Make sure we're calling this correctly
assert to_tab.workflow_id == self.workflow_id
# Generate a new slug: 9 bytes, base64-encoded, + and / becoming - and _.
# Mimics assets/js/utils.js:generateSlug()
slug = "step-" + secrets.token_urlsafe(9)
# last_relevant_delta_id is _wrong_, but we need to set it to
# something. See DuplicateTabCommand to understand the chicken-and-egg
# dilemma.
last_relevant_delta_id = self.last_relevant_delta_id
return self._duplicate_with_slug_and_delta_id(
to_tab, slug, last_relevant_delta_id
)
示例9: on_connect
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def on_connect(self, websocket, **kwargs):
await websocket.accept()
self.channel_name = secrets.token_urlsafe(32)
try:
self.invoice_id = int(websocket.path_params["model_id"])
except (ValueError, KeyError):
await websocket.close(code=WS_1008_POLICY_VIOLATION)
return
self.invoice = (
await models.Invoice.query.select_from(get_invoice())
.where(models.Invoice.id == self.invoice_id)
.gino.first()
)
if not self.invoice:
await websocket.close(code=WS_1008_POLICY_VIOLATION)
return
if self.invoice.status != "Pending":
await websocket.send_json({"status": self.invoice.status})
await websocket.close()
return
self.invoice = await crud.get_invoice(self.invoice_id, None, self.invoice)
self.subscriber, self.channel = await utils.make_subscriber(self.invoice_id)
settings.loop.create_task(self.poll_subs(websocket))
示例10: create_roll
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def create_roll() -> Tuple[Any, HTTPStatus, Dict[str, Any]]:
body = request.get_json(force=True)
if set(body.keys()) != {"dice"}:
raise BadRequest(f"Extra fields in {body!r}")
try:
n_dice = int(body["dice"])
except ValueError as ex:
raise BadRequest(f"Bad 'dice' value in {body!r}")
roll = [random.randint(1, 6) for _ in range(n_dice)]
identifier = secrets.token_urlsafe(8)
SESSIONS[identifier] = roll
current_app.logger.info(f"Rolled roll={roll!r}, id={identifier!r}")
headers = {"Location": url_for("roll.get_roll", identifier=identifier)}
return jsonify(
roll=roll, identifier=identifier, status="Created"
), HTTPStatus.CREATED, headers
示例11: _get_download_token
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def _get_download_token() -> str:
"""Return a download token from ~/.deeppavlov/token file.
If token file does not exists, creates the file and writes to it a random URL-safe text string
containing 32 random bytes.
Returns:
32 byte URL-safe text string from ~/.deeppavlov/token.
"""
token_file = Path.home() / '.deeppavlov' / 'token'
if not token_file.exists():
if token_file.parent.is_file():
token_file.parent.unlink()
token_file.parent.mkdir(parents=True, exist_ok=True)
token_file.write_text(secrets.token_urlsafe(32), encoding='utf8')
return token_file.read_text(encoding='utf8').strip()
示例12: test_token_defaults
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def test_token_defaults(self):
# Test that token_* functions handle default size correctly.
for func in (secrets.token_bytes, secrets.token_hex,
secrets.token_urlsafe):
with self.subTest(func=func):
name = func.__name__
try:
func()
except TypeError:
self.fail("%s cannot be called with no argument" % name)
try:
func(None)
except TypeError:
self.fail("%s cannot be called with None" % name)
size = secrets.DEFAULT_ENTROPY
self.assertEqual(len(secrets.token_bytes(None)), size)
self.assertEqual(len(secrets.token_hex(None)), 2*size)
示例13: refresh_user_token
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def refresh_user_token(user_name):
# check user exists first
user_exists = mongo_connection.mongo_check_user_exists(user_name)
if user_exists is False:
return jsonify({"user_name": False}), 403
# get current user data and update the token for him
try:
new_token = secrets.token_urlsafe()
app_exists, user_json = mongo_connection.mongo_get_user(user_name)
user_json["token"] = hash_secret(new_token)
except:
return jsonify({"token_refreshed": False}), 403
# update db
user_json = mongo_connection.mongo_update_user(user_name, user_json)
return jsonify({"token": new_token}), 200
# create new user
示例14: create_user
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def create_user(user_name):
# check app does't exists first
user_exists = mongo_connection.mongo_check_user_exists(user_name)
if user_exists is True:
return jsonify({"user_exists": True}), 403
else:
# check the request is passed with all needed parameters
try:
user_json = request.json
except:
return jsonify({"missing_parameters": True}), 400
try:
# hash the password & token, if not declared generates them randomly
password = hash_secret(return_sane_default_if_not_declared("password", user_json, secrets.token_urlsafe()))
token = hash_secret(return_sane_default_if_not_declared("token", user_json, secrets.token_urlsafe()))
except:
return jsonify({"missing_parameters": True}), 400
# update the db
user_json = mongo_connection.mongo_add_user(user_name, password, token)
return dumps(user_json), 200
# create new user_group
示例15: check_code
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_urlsafe [as 别名]
def check_code(self, request):
code, uid = (await request.text()).split("\n")
uid = int(uid)
if uid not in self._uid_to_code:
return web.Response(status=404)
if self._uid_to_code[uid] == code:
del self._uid_to_code[uid]
secret = secrets.token_urlsafe()
asyncio.ensure_future(asyncio.shield(self._clear_secret(secret)))
self._secret_to_uid[secret] = uid # If they just signed in, they automatically are authenticated
return web.Response(text=secret)
else:
return web.Response(status=401)