def pal_check_2(s): '''(str) -> bool Determine whether a string, s, is a palindrome. >>> pal_check_2('asdsa') True >>> pal_check_2('asd') False ''' if len(s) % 2 == 0: return s[:len(s) // 2] == reverse(s[(len(s) // 2):]) else: return s[:len(s) // 2] == reverse(s[(len(s) // 2) + 1:])
def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], [])
def setUp(self): """Define the test client and other test variables.""" self.client = APIClient() self.bucketlist_data = {'name': 'Go to Ibiza'} self.response = self.client.post( reverse('create'), self.bucketlist_data, format="json")
def test_past_question(self): """ The detail view of a question with a pub_date in the past displays the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)
def test_future_question(self): """ Questions with a pub_date in the future aren't displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_future_question(self): """ The detail view of a question with a pub_date in the future returns a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404)
def pal_check_1(s): ''' (str) -> bool Determine whether a string, s, is a palindrome by comparing the original string to the reversed string. >>> pal_check_1('strts') True >>> pal_check_1('asdf') False ''' return s == reverse(s)
def test_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] )
def test_past_question(self): """ Questions with a pub_date in the past are displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] )
def test_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions are displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] )
def test_signup_status_code(self): url = reverse('signup') response = self.client.get(url) self.assertEquals(response.status_code, 200)
def get_absolute_url(self): return reverse("detail", kwargs={"id": self.id})
def setUp(self): self.client = Client() self.url = reverse('index')
messages.success(request, f'Updated {size.upper()} {product.name} quantity to {bag[item_id]["items_by_size"][size]}') else: del bag[item_id]['items_by_size'][size] if not bag[item_id]['items_by_size']: bag.pop(item_id) messages.success(request, f'Removed size {size.upper()} {product.name} from your bag') else: if quantity > 0: bag[item_id] = quantity messages.success(request, f'Updated {product.name} quantity to {bag[item_id]}') else: bag.pop(item_id) messages.success(request, f'Removed {product.name} from your bag') request.session['bag'] = bag return redirect(reverse('view_bag')) def remove_from_bag(request, item_id): """Remove the item from the shopping bag""" try: product = get_object_or_404(Product, pk=item_id) size = None if 'product_size' in request.POST: size = request.POST['product_size'] bag = request.session.get('bag', {}) if size: del bag[item_id]['items_by_size'][size] if not bag[item_id]['items_by_size']:
def main(): """Main""" print "Enter any word and I'll spell it out backwards." inputStr = raw_input("Please, enter a word: ") print "%s" % reverse(inputStr)
try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist) # Повторное загрузка окна формы опроса return render(request, 'polls/detail.html', { # возвращает словарь со значениями 'question': question, 'error_messages': "You didn't select a choice" }) else: selected_choice.votes += 1 selected_choice.save() #Всегда возвращай HttpResponceRedirect after successfully # with post data избегаем повторную публикацию данных #user hits the back button return HttpResponseRedirect(reverse('polls:results', args=(question.id))) Разбор: 1 # request.POST['choice'] возвращает индетификатор выбранного варианта строки, всегда возвращает строку 2 # request.POST['choice'] будет вызывать KeyError если ключ choice не был представлен в POST будет повторно отображать форму вопроса # сообщение об ошибке если choice на задано 3 # HttpResponseRedirect принимает один аргумент: URL-адрес, на который будет перенаправлен пользователь #Как указано выше в комментарии Python, вы должны всегда возвращать HttpResponseRedirect после успешной # обработки данных POST!!!хорошая практика 4 # функцию reverse() в конструкторе HttpResponseRedirect. Эта функция помогает избежать жесткого кодирования URL-адреса в #функции представления. # '/polls/3/results/'
#!/home/lazarop/miniconda3/envs/python/bin/python from reverse import * reverse("she_sells_seashells.txt")
def test_list(): assert resolve(f"/list").view_name == "emaillist:display" assert reverse("emaillist:display") == "/list"
def test_add(): assert reverse("emaillist:add") == "/add" assert resolve("/add").view_name == "emaillist:add"
# Create your views here. def all_products(request): """ all Products page view """ products = Product.objects.all() query = None if request.GET: if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You did not enter any search criteria!") return redirect(reverse('products')) queries = Q(name__icontains=query) | Q(description__icontains=query) | Q(gender__icontains=query) products = products.filter(queries) context = { 'products': products, 'search_term': query, } return render(request, 'products/products.html', context) def product_detail(request, product_id): """ Showing individual product details """