本文整理汇总了Python中api.models.User方法的典型用法代码示例。如果您正苦于以下问题:Python models.User方法的具体用法?Python models.User怎么用?Python models.User使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类api.models
的用法示例。
在下文中一共展示了models.User方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createdb
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def createdb(testdata=False):
app = create_app()
with app.app_context():
db.drop_all()
db.create_all()
if testdata:
classes = ['Algebra', 'Literature', 'Chemistry', 'Spanish',
'Game Development', 'History', 'Music', 'Psychology',
'Science', 'Photography', 'Drama', 'Business',
'Python Programming']
for name in classes:
c = Class(name=name)
db.session.add(c)
u = User(username='miguel', password='python')
db.session.add(u)
db.session.commit()
示例2: create
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def create(request):
if request.user.is_authenticated() and not request.user.is_anonymous():
return redirect('/user/' + request.user.username + '/')
if request.method == "POST":
form = forms.CreateUserForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(**form.cleaned_data)
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
preferences = models.UserPreferences.objects.create(user=user)
login(request, user)
return redirect('/addaccount/' + ('?next=' + urlquote(request.GET['next']) if 'next' in request.GET else ''))
else:
form = forms.CreateUserForm()
context = globalContext(request)
context['form'] = form
context['current'] = 'create'
context['next'] = request.GET.get('next', None)
return render(request, 'create.html', context)
示例3: adduser
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def adduser(username):
"""Register a new user."""
from getpass import getpass
password = getpass()
password2 = getpass(prompt='Confirm: ')
if password != password2:
import sys
sys.exit('Error: passwords do not match.')
db.create_all()
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
print('User {0} was registered successfully.'.format(username))
示例4: setUp
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def setUp(self):
self.app = create_app('test_config')
self.ctx = self.app.app_context()
self.ctx.push()
db.drop_all()
db.create_all()
u = User(username=self.default_username,
password=self.default_password)
db.session.add(u)
db.session.commit()
self.client = TestClient(self.app, u.generate_auth_token(), '')
示例5: test_password_auth
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def test_password_auth(self):
self.app.config['USE_TOKEN_AUTH'] = False
good_client = TestClient(self.app, self.default_username,
self.default_password)
rv, json = good_client.get('/api/v1.0/students/')
self.assertTrue(rv.status_code == 200)
self.app.config['USE_TOKEN_AUTH'] = True
u = User.query.get(1)
good_client = TestClient(self.app, u.generate_auth_token(), '')
rv, json = good_client.get('/api/v1.0/students/')
self.assertTrue(rv.status_code == 200)
示例6: handle
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def handle(self, *args, **options):
"Register handle for filename option"
if options['filename']:
# Clean old updates
print("Cleaning old DB entries...")
User.objects.all().delete()
print("Registering users...")
self._populate_users(options['filename'])
else:
print("No filename given... :-(", file=sys.stderr)
示例7: _populate_users
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def _populate_users(self, filename):
"Open and parse a csv file, and register users"
try:
f = open(filename)
except IOError as error:
print("I/O error while opening file: <%s>" % filename,\
file=sys.stderr)
return
for line in f:
try:
line = line.split('\n')[0]
if line[0] == '#':
continue
uid = int(line.split(',')[0])
zipcode = str(line.split(',')[1])
city = str(line.split(',')[2])
state = str(line.split(',')[3])
sex = int(line.split(',')[4])
race = int(line.split(',')[5])
income = self._normalized_income(int(line.split(',')[6]))
except IndexError as error:
print("Malformed line: <%s>" % line, file=sys.stderr)
continue
u = User(uid, zipcode, city, state, sex, race, income)
u.save()
print("User:%d saved"% (uid))
transaction.commit()
f.close()
示例8: _create_request_context
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def _create_request_context(
cls,
customer_data,
user_data,
create_customer=True,
create_user=True,
create_tenant=False,
is_admin=True,
is_cost_management=True,
):
"""Create the request context for a user."""
customer = customer_data
account = customer.get("account_id")
if create_customer:
cls.customer = cls._create_customer(account, create_tenant=create_tenant)
identity = {
"identity": {
"account_number": account,
"type": "User",
"user": {
"username": user_data["username"],
"email": user_data["email"],
"is_org_admin": is_admin,
"access": user_data["access"],
},
},
"entitlements": {"cost_management": {"is_entitled": is_cost_management}},
}
json_identity = json_dumps(identity)
mock_header = b64encode(json_identity.encode("utf-8")).decode("utf-8")
request = Mock()
request.META = {RH_IDENTITY_HEADER: mock_header}
if create_user:
tempUser = User(username=user_data["username"], email=user_data["email"], customer=cls.customer)
tempUser.save()
request.user = tempUser
else:
request.user = user_data["username"]
request_context = {"request": request}
return request_context
示例9: __call__
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def __call__(self, function):
"""Call method."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
user = self.user
user["access"] = self.access
dev_middleware = "koku.dev_middleware.DevelopmentIdentityHeaderMiddleware"
middleware = settings.MIDDLEWARE
if dev_middleware not in middleware:
middleware.insert(5, dev_middleware)
identity = {
"identity": {"account_number": "10001", "type": "User", "user": user},
"entitlements": {"cost_management": {"is_entitled": "True"}},
}
with override_settings(DEVELOPMENT=True):
with override_settings(DEVELOPMENT_IDENTITY=identity):
with override_settings(MIDDLEWARE=middleware):
request_context = IamTestCase._create_request_context(self.customer, user)
middleware = DevelopmentIdentityHeaderMiddleware()
middleware.process_request(request_context["request"])
result = function(*args, **kwargs)
return result
return wrapper
示例10: password_reset_confirm
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def password_reset_confirm(request, uidb64, token, template_name):
try:
uid = urlsafe_base64_decode(uidb64)
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
accounts_with_transfer_code = 0
if user is not None:
accounts_with_transfer_code = user.accounts_set.exclude(transfer_code__isnull=True).exclude(transfer_code__exact='').count()
response = password_reset_confirm_view(request, uidb64=uidb64, token=token, extra_context={'accounts_with_transfer_code': accounts_with_transfer_code}, template_name=template_name)
if isinstance(response, HttpResponseRedirect) and user is not None:
accounts_with_transfer_code = user.accounts_set.all().update(transfer_code='')
return response
示例11: ajaxfollowers
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def ajaxfollowers(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'followlist.html', { 'follow': [u.user for u in user.followers.all()],
})
示例12: ajaxfollowing
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def ajaxfollowing(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'followlist.html', { 'follow': user.preferences.following.all(),
})
示例13: report
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def report(request, account=None, eventparticipation=None, user=None, activity=None):
context = globalContext(request)
context['report'] = None
context['account'] = None
context['eventparticipation'] = None
context['fake_user'] = None
context['activity'] = None
if account:
context['account'] = findAccount(int(account), context.get('accounts', []), forceGetAccount=True)
if not context['account']: raise Http404
elif user:
context['fake_user'] = get_object_or_404(models.User, username=user)
elif activity:
context['activity'] = get_object_or_404(models.Activity, pk=activity)
if context['activity'].message == 'Custom':
context['activity'].message_data = context['activity'].message_data[:100]
context['activity'].localized_message = _localized_message_activity(context['activity'])
elif eventparticipation:
context['eventparticipation'] = get_object_or_404(models.EventParticipation.objects.select_related('event', 'account', 'account__owner'), pk=eventparticipation)
if request.user.is_authenticated():
try: context['report'] = models.ModerationReport.objects.get(reported_by=request.user, fake_account=context['account'], fake_eventparticipation=context['eventparticipation'], fake_user=context['fake_user'], fake_activity=context['activity'])
except ObjectDoesNotExist: pass
if request.method == 'POST':
context['form'] = forms.ModerationReportForm(request.POST, request.FILES, instance=context['report'], request=request, account=context['account'], eventparticipation=context['eventparticipation'], user=context['fake_user'], activity=context['activity'])
if context['form'].is_valid():
context['report'] = context['form'].save()
context['reported'] = True
else:
context['form'] = forms.ModerationReportForm(instance=context['report'], request=request, account=context['account'], eventparticipation=context['eventparticipation'], user=context['fake_user'], activity=context['activity'])
if context['report']:
context['report_images'] = context['report'].images.all()
return render(request, 'report.html', context)
示例14: aboutview
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def aboutview(request):
context = globalContext(request)
context['show_paypal'] = 'show_paypal' in request.GET
if not settings.HIGH_TRAFFIC:
users = models.User.objects.filter(Q(is_staff=True) | Q(preferences__status__isnull=False)).exclude(is_staff=False, preferences__status='').order_by('-is_superuser', 'preferences__status', 'username').select_related('preferences')
users = users.annotate(verifications_done=Count('verificationsdone'))
context['staff'] = []
context['donators_low'] = []
context['donators_high'] = []
for user in users:
if user.is_staff:
context['staff'].append(user)
if user.preferences.status == 'THANKS' or user.preferences.status == 'SUPPORTER' or user.preferences.status == 'LOVER' or user.preferences.status == 'AMBASSADOR':
context['donators_low'].append(user)
elif user.preferences.status == 'PRODUCER' or user.preferences.status == 'DEVOTEE':
context['donators_high'].append(user)
context['total_donators'] = settings.TOTAL_DONATORS
context['artists'] = [artist for artist in raw.community_artists if artist[1] != 'klab']
contests = contest_models.Contest.objects.filter(begin__lte=timezone.now()).filter(Q(image_by__isnull=False) | Q(result_image_by__isnull=False)).select_related('image_by', 'result_image_by')
context['graphic_designers'] = raw.all_graphic_designers[:]
for contest in contests:
if contest.image_by and contest.image:
context['graphic_designers'].append((_imageurl(contest.image), contest.image_by.username))
if contest.result_image_by and contest.result_image:
context['graphic_designers'].append((_imageurl(contest.result_image), contest.result_image_by.username))
return render(request, 'about.html', context)
示例15: setUp
# 需要导入模块: from api import models [as 别名]
# 或者: from api.models import User [as 别名]
def setUp(self):
self.app = create_app('test_config')
self.ctx = self.app.app_context()
self.ctx.push()
db.drop_all()
db.create_all()
u = User(username=self.default_username,
password=self.default_password)
db.session.add(u)
db.session.commit()
self.client = TestClient(self.app, u.generate_auth_token(), '')
self.catalog = self._get_catalog()