def webfinger_view(request):
"""Generate a webfinger document."""
q = request.GET.get("q")
if not q:
raise Http404()
username = q.split("@")[0]
if username.startswith("acct:"):
username = username.replace("acct:", "", 1)
user = get_object_or_404(User, username=username)
# Create webfinger document
webfinger = generate_legacy_webfinger(
"diaspora",
handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN),
host=settings.SOCIALHOME_URL,
guid=str(user.profile.guid),
public_key=user.profile.rsa_public_key
)
return HttpResponse(webfinger, content_type="application/xrd+xml")
python类HttpResponse()的实例源码
def hcard_view(request, guid):
"""Generate a hcard document.
For local users only.
"""
try:
profile = get_object_or_404(Profile, guid=guid, user__isnull=False)
except ValueError:
raise Http404()
hcard = generate_hcard(
"diaspora",
hostname=settings.SOCIALHOME_URL,
fullname=profile.name,
firstname=profile.get_first_name(),
lastname=profile.get_last_name(),
photo300=profile.safer_image_url_large,
photo100=profile.safer_image_url_medium,
photo50=profile.safer_image_url_small,
searchable="true" if profile.public else "false",
guid=profile.guid,
username=profile.user.username,
public_key=profile.rsa_public_key,
)
return HttpResponse(hcard)
def auth(func):
@wraps(func)
def _decorator(request, *args, **kwargs):
auth = get_auth()
if auth.get('disable', False) is True:
return func(request, *args, **kwargs)
if 'authorized_ips' in auth:
ip = get_client_ip(request)
if is_authorized(ip, auth['authorized_ips']):
return func(request, *args, **kwargs)
prepare_credentials(auth)
if request.META.get('HTTP_AUTHORIZATION'):
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ')
if authmeth.lower() == 'basic':
auth = base64.b64decode(auth).decode('utf-8')
username, password = auth.split(':')
if (username == HEARTBEAT['auth']['username'] and
password == HEARTBEAT['auth']['password']):
return func(request, *args, **kwargs)
response = HttpResponse(
"Authentication failed", status=401)
response['WWW-Authenticate'] = 'Basic realm="Welcome to 1337"'
return response
return _decorator
def index(request):
if request.method == 'POST':
form = SMSForm(request.POST)
if form.is_valid():
numbers = form.cleaned_data['recipient_numbers']
content = form.cleaned_data['content']
for number in numbers:
pass
# send_sms(number, content)
return HttpResponse(', '.join(numbers))
else:
form = SMSForm(
initial={
'recipient_numbers': '010-2995-3874, 01029953874, 01023412, 293849323232, 02394090930',
}
)
context = {
'form': form,
}
return render(request, 'common/index.html', context)
def serve(self, request):
if "format" in request.GET:
if request.GET['format'] == 'ical':
# Export to ical format
response = HttpResponse(
export_event(self, 'ical'),
content_type='text/calendar',
)
response['Content-Disposition'] = (
'attachment; filename={}.ics'.format(self.slug)
)
return response
else:
# Unrecognised format error
message = (
'Could not export event\n\nUnrecognised format: {}'.format(
request.GET['format']
)
)
return HttpResponse(message, content_type='text/plain')
else:
# Display event page as usual
return super(EventPage, self).serve(request)
def serve(self, request, path):
# the following code is largely borrowed from `django.views.static.serve`
# and django-filetransfers: filetransfers.backends.default
fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path)
if not os.path.exists(fullpath):
raise Http404('"{0}" does not exist'.format(fullpath))
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
content_type = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified(content_type=content_type)
response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type)
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
# filename = os.path.basename(path)
# response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename))
return response
def response(status, data):
hr = HttpResponse()
hr['Access-Control-Allow-Origin'] = '*'
hr['Content-Type'] = 'application/json'
hr['charset'] = 'utf-8'
hr.status_code = status
if type(data) == str or type(data) == unicode:
data = {
'message': data,
}
try:
hr.write(json.dumps(data))
except:
try:
hr.write(json.dumps(data, default=json_util.default))
except:
hr.status_code = 500
hr.write(json.dumps({
'error': "json serialize failed",
}))
return hr
def index(request):
enable_hstore()
try:
if request.method == 'POST':
json_data = json.loads(request.body)
meta = json_data[u'meta']
# API v1
if meta[u'v'] == 1:
return handle_v1(json_data)
else:
raise NonImplementedVersionException()
except IntegrityError as e:
logging.warning(e.message)
logging.warning("Forcing full sync from pipedrive")
PipedriveModel.sync_from_pipedrive()
return HttpResponse("Hello, world!")
def find_random_image(request):
"""
Randomly get an image and return the relative url
"""
item = KioskItem.objects.filter(active=True).order_by('?').first()
if item is None:
raise Http404("No active kiosk items found")
response_data = {
"id": item.id,
"url": item.image.url,
}
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
def resolve(request):
mimetype = 'application/json'
data = {}
if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
data['entity'] = request.POST['entity']
data['status'] = 0
data['timestamp'] = datetime.datetime.now().timestamp()
data['output'] = "resolve request by %s" % (request.user.username)
data['result'] = 'okay'
sensu_event_resolve(data)
Channel('background-alert').send(dict(data))
return HttpResponse(json.dumps(data), mimetype)
#@login_required(login_url=reverse_lazy('login'))
def rmClient(request):
mimetype = 'application/json'
data = {}
if request.method == 'POST' and 'client' in request.POST and request.POST['client'] != '':
data['client'] = request.POST['client']
data['status'] = 0
data['timestamp'] = datetime.datetime.now().timestamp()
if sensu_client_delete(data):
data['result'] = 'okay'
else:
data['result'] = 'failed deleting ' + data['client']
return HttpResponse(json.dumps(data), mimetype)
#@login_required(login_url=reverse_lazy('login'))
def twilio_say(request):
if 'api_token' not in request.GET or request.GET['api_token'] != settings.TWILIO_CALLBACK_API_TOKEN:
return HttpResponse('Unauthorized', status=401)
try:
if 'CallStatus' in request.POST:
for k in request.POST:
logger.debug("***twilio_say got CallStatus in request %s : %s" % (k, request.POST[k]))
except:
pass
if 'msg' in request.GET and request.GET['msg'] != '':
logger.debug("twilio_say building xml for twilio API message: [%s]" % request.GET['msg'])
r = twiml.Response()
r.say(request.GET['msg'], voice='alice')
r.hangup()
return HttpResponse(r, content_type='text/xml')
return HttpResponse('Unauthorized', status=401)
def entity_history(request):
data = []
mimetype = 'application/json'
if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
entity = request.POST['entity']
logger.debug("view entity_history user: %s entity: %s" % (request.user.username, entity))
for history_data in r.lrange('history_entity_' + entity, 0, 100):
data.append(pickle.loads(history_data))
return HttpResponse(json.dumps(data), mimetype)
#@login_required(login_url=reverse_lazy('login'))
def entity_notify_history(request):
data = []
mimetype = 'application/json'
if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
entity = request.POST['entity']
logger.debug("view entity_notify_history user: %s entity: %s" % (request.user.username, entity))
for history_data in r.lrange('notifyhistory_entity_' + entity, 0, 100):
data.append(pickle.loads(history_data))
return HttpResponse(json.dumps(data), mimetype)
#@login_required(login_url=reverse_lazy('login'))
def check_config(request):
mimetype = 'application/json'
data = {}
if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
client_name, check_name = request.POST['entity'].split(':')
#check_name = 'check_gw_tomcat_errors_1h'
#data = cache.get('check_' + check_name)
data = cache.get('check_' + request.POST['entity'])
return HttpResponse(json.dumps(data), mimetype)
#@login_required(login_url=reverse_lazy('login'))
def change_password(request):
"""
Sets the new password for user.
"""
if request.is_ajax():
change_password_form = ChangePasswordForm(request.POST)
if change_password_form.is_valid():
with transaction.atomic():
if request.user.check_password(change_password_form.cleaned_data['prev_password']):
request.user.set_password(change_password_form.cleaned_data['new_password'])
request.user.save()
logger.info("User '{}' changed his password successfully.".format(request.user))
changed_password.delay(request.user.username, request.user.email)
return HttpResponse(json.dumps('?????? ??????? ???????!'), content_type='application/json')
else:
return HttpResponse(json.dumps('?????? ?????? ?? ?????????. ????????? ?? ??????? ??????.'),
content_type='application/json')
else:
return HttpResponse(status=404)
def is_user_exists(request):
"""
Checks if user is exists. If exists return True, else False.
"""
if request.is_ajax():
is_user_exists_form = IsUserExistsForm(request.GET)
if is_user_exists_form.is_valid():
try:
User.objects.get(username=is_user_exists_form.cleaned_data['username'])
return HttpResponse(json.dumps(True), content_type='application/json')
except ObjectDoesNotExist:
return HttpResponse(json.dumps(False), content_type='application/json')
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def is_mail_exists(request):
"""
Checks if mail is exists. If exists return True, else False.
"""
if request.is_ajax():
is_mail_exists_form = IsMailExistsForm(request.GET)
if is_mail_exists_form.is_valid():
try:
User.objects.get(email=is_mail_exists_form.cleaned_data['email'])
return HttpResponse(json.dumps(True), content_type='application/json')
except ObjectDoesNotExist:
return HttpResponse(json.dumps(False), content_type='application/json')
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def selected_category(request, category_id):
"""
Returns page with selected category.
"""
if request.method == 'GET':
category = Category.objects.get(id=category_id)
books = Book.objects.filter(id_category=category).order_by('book_name')
filtered_books = Book.exclude_private_books(request.user, books)
context = {'category': category, 'books': filtered_books, 'category_number': category_id}
return render(request, 'selected_category.html', context)
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def find_books(request):
"""
Generates list with books of data which user entered. At first it check full equality in name,
after tries to check if contains some part of entered data.
"""
if request.is_ajax():
search_book_form = SearchBookForm(request.GET)
if search_book_form.is_valid():
search_data = search_book_form.cleaned_data['data']
filtered_books = Book.exclude_private_books(request.user, Book.fetch_books(search_data))
books = Book.generate_books(filtered_books)
for book in books:
book['name'] = escape(book['name'])
book['author'] = escape(book['author'])
return HttpResponse(json.dumps(books), content_type='application/json')
else:
return HttpResponse(status=404)
def remove_book_from_home(request):
"""
Removes book from list of user's added books.
"""
if request.is_ajax():
book_form = BookHomeForm(request.POST)
if book_form.is_valid():
AddedBook.objects.get(id_user=TheUser.objects.get(id_user=request.user),
id_book=Book.objects.get(id=book_form.cleaned_data['book'])).delete()
logger.info("User '{}' removed book with id: '{}' from his own library."
.format(request.user, book_form.cleaned_data['book']))
return HttpResponse(json.dumps(True), content_type='application/json')
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def change_rating(request):
if request.is_ajax():
rating_form = ChangeRatingForm(request.POST)
if rating_form.is_valid():
with transaction.atomic():
set_rating(request, rating_form)
book_rating = BookRating.objects.filter(id_book=Book.objects.get(id=rating_form.cleaned_data['book']))
data = {'avg_rating': round(book_rating.aggregate(Avg('rating'))['rating__avg'], 1),
'rating_count': '({})'.format(book_rating.count())}
return HttpResponse(json.dumps(data), content_type='application/json')
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def generate_books(request):
"""
Returns a list of books.
"""
if request.is_ajax():
book_list_form = GenerateBooksForm(request.GET)
if book_list_form.is_valid():
list_of_books = Book.generate_existing_books(book_list_form.cleaned_data['part'])
return HttpResponse(json.dumps(list_of_books), content_type='application/json')
else:
return HttpResponse(status=404)
# ----------------------------------------------------------------------------------------------------------------------
def set_current_page(request):
"""
Changes current readed page for book of user.
"""
if request.is_ajax():
pages_form = SetCurrentPageForm(request.POST)
if pages_form.is_valid():
with transaction.atomic():
book = Book.objects.get(id=pages_form.cleaned_data['book'])
user = TheUser.objects.get(id_user=request.user)
added_book = AddedBook.objects.get(id_book=book, id_user=user)
added_book.last_page = pages_form.cleaned_data['page']
added_book.save()
logger.info("User '{}' on book with id: '{}' changed page to: '{}'."
.format(user, book.id, pages_form.cleaned_data['page']))
return HttpResponse(json.dumps(True), content_type='application/json')
else:
return HttpResponse(status=404)
def like(request):
"""
kullan?c? be?endi?inde vya be?enmedi?inde ekrandaki skoru otomatik
update eder
"""
id = request.GET.get("id", default=None)
like = request.GET.get("like")
obj = get_object_or_404(Post, id=int(id))
if like == "true":
# f objesi veri tabanindaki ilgili sutunun degerini cekerek
# atama yapmak yerine arttirma veya azaltma yapmamizi saglar.
obj.score = F("score") + 1
obj.save(update_fields=["score"])
elif like == "false":
obj.score = F("score") - 1
obj.save(update_fields=["score"])
else:
return HttpResponse(status=400)
obj.refresh_from_db()
return JsonResponse({"like": obj.score, "id": id})
def webhook(request):
webhook_secret = 'YOUR_WEBHOOK_SECRET_HERE'
if request.POST.get('secret') != webhook_secret:
return HttpResponse("Invalid webhook secret", 'text/plain', 403)
if request.POST.get('event') == 'incoming_message':
content = request.POST.get('content')
from_number = request.POST.get('from_number')
phone_id = request.POST.get('phone_id')
# do something with the message, e.g. send an autoreply
return HttpResponse(json.dumps({
'messages': [
{'content': "Thanks for your message!"}
]
}), 'application/json')
def Login(request):
if(request.method == "POST"):
UserAccount = request.POST.get('name');#?????
UserPassword = request.POST.get('password');#??????
userInfo = getUserToSQL(UserAccount,UserPassword);#????? ??????
if(userInfo):
if userInfo[0].User_Role == 0:#?????
request.session['CurrentUserId'] = userInfo[0].User_Id;#????????
CurrentId = request.session.get('CurrentUserId');
CurrentUser = getUserToSQLForId(CurrentId)[0];
objs = UserInfo.objects.filter(User_Role = 1);#????????
return render(request,'admin.html',{'CurrentUser':CurrentUser,'objs':objs});
else:#??????
request.session['CurrentUserId'] = userInfo[0].User_Id;
CurrentId = request.session.get('CurrentUserId');
CurrentUser = getUserToSQLForId(CurrentId)[0];
signStatus = SignStatus.objects.filter(Sign_Status_User=CurrentUser)[0];#??????
if(signStatus.Sign_Status == True):#????????
return render(request, 'normalOne.html', {'CurrentUser': CurrentUser, 'signStatus': signStatus});
else:#????????
return render(request,'normalTwo.html',{'CurrentUser':CurrentUser,'signStatus':signStatus});
return HttpResponse("????????????");#?????????
#????
def get(self, request, *args, **kwargs):
try:
uid = force_text(urlsafe_base64_decode(kwargs['uid64']))
user = UserModel.objects.get(pk=uid)
except Exception as e:
logger.info(e)
user = None
if user is not None and account_activation_token.check_token(user, kwargs['token']):
email_address = user.emailaddress_set.first()
email_address.verified = True
email_address.save()
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
# return redirect('home')
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
return HttpResponse('Activation link is invalid!')
def set_reminder(request):
current_username = request.POST.get('username')
current_longitude = request.POST.get('longitude')
current_latitude = request.POST.get('latitude')
current_reminder_title = request.POST.get('reminder_title')
current_reminder_text = request.POST.get('reminder_text')
try:
user=User.objects.get(username=current_username)
except Exception as e:
return HttpResponse("username is not registered")
reminder = Reminder(username = user, longitude = current_longitude,
latitude = current_latitude, reminder_title = current_reminder_title, reminder_text = current_reminder_text)
reminder.save()
return HttpResponse("reminder has been set")
def delete_reminder(request):
current_username = request.POST.get('username')
reminder_id = request.POST.get('id')
try:
user=User.objects.get(username=current_username)
except Exception as e:
return HttpResponse("username is not registered")
#setting = SaveSettings.objects.get(latitude = current_latitude)
deleted_reminder = Reminder.objects.get(pk = reminder_id)
deleted_reminder.delete()
return HttpResponse("reminder deleted sucessfully")
#Friends Table View