本文整理汇总了Python中models.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register
def register(self):
if request.method == u'POST':
client_key = self.generate_client_key()
secret = self.generate_client_secret()
# TODO: input sanitisation?
name = request.form.get(u"name")
description = request.form.get(u"description")
callback = request.form.get(u"callback")
pubkey = request.form.get(u"pubkey")
# TODO: redirect?
# TODO: pubkey upload
# TODO: csrf
info = {
u"client_key": client_key,
u"name": name,
u"description": description,
u"secret": secret,
u"pubkey": pubkey
}
client = Client(**info)
client['callbacks'].append(callback)
client['resource_owner_id'] = g.user['_id']
client_id = Client.insert(client)
g.user.client_ids.append(client_id)
User.get_collection().save(g.user)
return render_template(u"client.html", **info)
else:
clients = Client.get_collection().find({'_id': {'$in':
[ObjectId(oid) for oid in g.user.client_ids]}})
return render_template(u"register.html", clients=clients)
示例2: authorize
def authorize():
if request.method == "GET":
print "123445566"
context_id = None
# scopes requesting resource accesses
resource_scopes = []
for scope in request.args["scope"].split(" "):
if scope.startswith("launch:"):
_, context_id = scope.rsplit(":", 1)
elif scope.startswith("patient/") or scope.startswith("user/"):
resource_scopes.append(scope)
if context_id is None:
# create launch context for app launched outside of EHR env
# TODO clean this up
return redirect(
"%s?%s" % (url_for("auth.create_context"), urlencode({"auth_req": json.dumps(request.args)}))
)
assert request.args["response_type"] == "code"
# find app requested this authorization
app = App.query.filter_by(
client_id=request.args["client_id"], redirect_uri=request.args["redirect_uri"]
).first()
assert app is not None
client = Client(
authorizer=request.session.user,
app=app,
state=request.args.get("state"),
scope=request.args["scope"],
context_id=context_id,
)
db.session.add(client)
ctx = Context.query.get(context_id)
# id of patient selected in launch time, could be none
pid = json.loads(ctx.context).get("Patient")
# parse requested scopes
scopes = [OAuthScope(scp_str, pid) for scp_str in resource_scopes]
readable_accesses = map(OAuthScope.to_readable, scopes)
# we grant access despite user's reaction so that we don't have to keep tract of requested scope
# security is being taken care of by marking the authorized client as un authorized
for scope in scopes:
scope.get_access_from_user(request.session.user, client)
db.session.commit()
return render_template(
"authorization.html", appname=app.name, accesses=readable_accesses, auth_code=client.code
)
else:
client = Client.query.filter_by(code=request.form["auth_code"]).first()
assert client is not None
app = App.query.filter_by(client_id=client.client_id).first()
redirect_uri = app.redirect_uri
if request.form["authorize"] == "yes":
# authorize the client and redirect
client.authorized = True
db.session.commit()
redirect_args = {"code": request.form["auth_code"]}
if client.state is not None:
redirect_args["state"] = client.state
else:
redirect_args = {"error": "Authorization declined"}
return redirect("%s?%s" % (redirect_uri, urlencode(redirect_args)))
示例3: register
def register(self):
if request.method == u'POST':
client_key = self.generate_client_key()
secret = self.generate_client_secret()
# TODO: input sanitisation?
name = request.form.get(u"name")
description = request.form.get(u"description")
callback = request.form.get(u"callback")
pubkey = request.form.get(u"pubkey")
# TODO: redirect?
# TODO: pubkey upload
# TODO: csrf
info = {
u"client_key": client_key,
u"name": name,
u"description": description,
u"secret": secret,
u"pubkey": pubkey
}
client = Client(**info)
client.callbacks.append(Callback(callback))
client.resource_owner = g.user
db_session.add(client)
db_session.commit()
return render_template(u"client.html", **info)
else:
clients = g.user.clients
return render_template(u"register.html", clients=clients)
示例4: delete_client
def delete_client(self, cmd, anon_ch):
valid, msg, owner = self.check_del_params(cmd)
if not valid:
anon_ch.put({'status': 'error',
'message': 'Invalid parameters sent: {}'.format(msg)})
return None
try:
_, ag = self.get_agave(cmd['tenant'], owner)
except ClientException as e:
anon_ch.put({'status': 'error',
'message': 'Could not generate an Agave client: {}'.format(e)})
return None
# remove the client from APIM
try:
ag.clients.delete(clientName=cmd['worker_id'])
except Exception as e:
anon_ch.put({'status': 'error',
'message': 'Not able to delete client from APIM. Exception: {}'.format(e)})
return None
# remove the client from the abaco db
try:
Client.delete_client(tenant=cmd['tenant'], client_key=cmd['client_id'])
except Exception as e:
anon_ch.put({'status': 'error',
'message': 'Not able to delete client from abaco db. Exception: {}'.format(e)})
return None
anon_ch.put({'status': 'ok',
'message': 'Client deleted.'})
示例5: test_one_report
def test_one_report(self):
client = Client(product=ProductData.killerapp_obj, cookie='123')
client.put()
report = Report(product=ProductData.killerapp_obj, client=client, status=REPORT_NEW, remote_ip='127.0.0.1', data='[]')
report.put()
response = self.get('/status/')
assert 'Queued Reports: 1' in str(response)
示例6: management
def management():
""" This endpoint is for vieweing and adding users and clients. """
if request.method == 'POST' and request.form['submit'] == 'Add User':
User.save(request.form['username'], request.form['password'])
if request.method == 'POST' and request.form['submit'] == 'Add Client':
Client.generate()
return render_template('management.html', users=User.all(),
clients=Client.all())
示例7: create
def create(self, validated_data):
client = Client(
name=validated_data['name'],
alias=validated_data['name'].lower(),
active=validated_data['active']
)
client.save()
return client
示例8: authorize
def authorize():
if request.method == 'GET':
context_id = None
# scopes requesting resource accesses
resource_scopes = []
for scope in request.args['scope'].split(' '):
if scope.startswith('launch:'):
_, context_id = scope.rsplit(':', 1)
elif scope.startswith('patient/') or scope.startswith('user/'):
resource_scopes.append(scope)
if context_id is None:
# create launch context for app launched outside of EHR env
# TODO clean this up
return redirect('%s?%s'% (url_for('auth.create_context'), urlencode({'auth_req': json.dumps(request.args)})))
assert request.args['response_type'] == 'code'
# find app requested this authorization
app = App.query.filter_by(
client_id=request.args['client_id'],
redirect_uri=request.args['redirect_uri']).first()
assert app is not None
client = Client(authorizer=request.session.user,
app=app,
state=request.args.get('state'),
scope=request.args['scope'],
context_id=context_id)
db.session.add(client)
ctx = Context.query.get(context_id)
# id of patient selected in launch time, could be none
pid = json.loads(ctx.context).get('Patient')
# parse requested scopes
scopes = [OAuthScope(scp_str, pid) for scp_str in resource_scopes]
readable_accesses = map(OAuthScope.to_readable, scopes)
# we grant access despite user's reaction so that we don't have to keep tract of requested scope
# security is being taken care of by marking the authorized client as un authorized
for scope in scopes:
scope.get_access_from_user(request.session.user, client)
db.session.commit()
return render_template('authorization.html',
appname=app.name,
accesses=readable_accesses,
auth_code=client.code)
else:
client = Client.query.filter_by(code=request.form['auth_code']).first()
assert client is not None
app = App.query.filter_by(client_id=client.client_id).first()
redirect_uri = app.redirect_uri
if request.form['authorize'] == 'yes':
# authorize the client and redirect
client.authorized = True
db.session.commit()
redirect_args = {'code': request.form['auth_code']}
if client.state is not None:
redirect_args['state'] = client.state
else:
redirect_args = {'error': 'Authorization declined'}
return redirect('%s?%s'% (redirect_uri, urlencode(redirect_args)))
示例9: client
def client():
item = Client(
client_id=gen_salt(40),
client_secret=gen_salt(50),
_redirect_uris='/',
is_confidential=True
)
db.session.add(item)
db.session.commit()
return make_response(json.dumps(item.dict()), 200)
示例10: test_parse_client
def test_parse_client(self):
response = '''
{"response":[{"id":"107111","name":"Ford","day_limit":170,"all_limit":3000}]}
'''
account = AccountFactory(remote_id=1)
instance = Client(account=account, fetched=datetime.now())
instance.parse(json.loads(response)['response'][0])
instance.save(commit_remote=False)
self.assertEqual(instance.account, account)
self.assertEqual(instance.remote_id, 107111)
self.assertEqual(instance.name, 'Ford')
self.assertEqual(instance.day_limit, 170)
self.assertEqual(instance.all_limit, 3000)
示例11: clients_add
def clients_add(request):
if request.method == "POST":
add_form = ClientAddForm(request.POST)
if add_form.is_valid():
new_cl = Client(
name=add_form.cleaned_data["name"],
address=add_form.cleaned_data["address"],
zip_code=add_form.cleaned_data["zip_code"],
country=add_form.cleaned_data["country"],
)
new_cl.save()
return HttpResponseRedirect("/clients/")
else:
add_form = ClientAddForm()
return render_to_response("storage/clients_add.html", {"form": add_form}, context_instance=RequestContext(request))
示例12: get_rsa_key
def get_rsa_key(self, client_key):
client = Client.find_one({'client_key':client_key})
if client:
return client.get('pubkey')
else:
return None
示例13: get_client_secret
def get_client_secret(self, client_key):
client = Client.find_one({'client_key':client_key})
if client:
return client.get('secret')
else:
return None
示例14: announce
def announce(request):
try:
params = torUtils.getParams(request.get_full_path()) # <-- Add this to models
ih = params[u'info_hash'][0]
# Match params to grab a specific torrent
t = Torrent.getTorrent(info_hash=ih)
# Check whether this is a new or returning client
c = t.getPeer(ip=request.META["REMOTE_ADDR"])
if c.size == 0:
c = Client.create(n = params['name'], i = request.META["REMOTE_ADDR"], p = params['port'], ih = params[u'info_hash'][0])
else:
# Parse old client
c = c[0]
c.update(params["event"])
except Exception as e:
print "Torrent not found; ", e
# return HttpResponse("Newp!")
# Match client against list of known users
# -- Seeding:
# -- Leeching:
# -- Loading:
# -- Inactive:
# If no announce, double-check peer connections, and send a new list
return HttpResponse("Fixthis")
示例15: createUser
def createUser(request):
_udid = request.GET['udid']
_tokenId = request.GET['tokenId']
_bundleId = request.GET['bundleId']
userId = ""
try :
user = Client.objects.get(udid =_udid)
user.tokenId = _tokenId
user.bundleId = _bundleId
userId = user.id
user.save()
except :
add_to_db = Client(udid=_udid,tokenId=_tokenId,bundleId=_bundleId)
add_to_db.save()
userId= add_to_db.id
return JSONResponse({'userId':userId})