本文整理汇总了Python中questions.models.Question类的典型用法代码示例。如果您正苦于以下问题:Python Question类的具体用法?Python Question怎么用?Python Question使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Question类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_from_url
def test_from_url(self):
"""Verify question returned from valid URL."""
q = question(save=True)
eq_(q, Question.from_url('/en-US/questions/%s' % q.id))
eq_(q, Question.from_url('/es/questions/%s' % q.id))
eq_(q, Question.from_url('/questions/%s' % q.id))
示例2: handle
def handle(self, *args, **options):
Question.objects.all().delete()
Answer.objects.all().delete()
print('Deleted existing data')
answers = []
with open(settings.BASE_DIR + '/../' + self.csv_file, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
next(reader, None)
for row in reader:
if(len(answers) > 80):
save_answers(answers)
answers = []
q = Question(question=row[0])
q.save()
print('Saved question with id ' + str(q.id));
answers.append(Answer(question=q, choice=row[1], correct=True))
for i in row[2].split(','):
answers.append(Answer(question=q, choice=i, correct=False))
save_answers(answers)
示例3: test_cron_updates_counts
def test_cron_updates_counts(self):
q = question(save=True)
self.refresh()
eq_(q.num_votes_past_week, 0)
# NB: Need to call .values_dict() here and later otherwise we
# get a Question object which has data from the database and
# not the index.
document = (Question.search()
.values_dict('question_num_votes_past_week')
.filter(id=q.id))[0]
eq_(document['question_num_votes_past_week'], 0)
vote = questionvote(question=q, anonymous_id='abc123')
vote.save()
q.num_votes_past_week = 0
q.save()
update_weekly_votes()
self.refresh()
q = Question.objects.get(pk=q.pk)
eq_(1, q.num_votes_past_week)
document = (Question.search()
.values_dict('question_num_votes_past_week')
.filter(id=q.id))[0]
eq_(document['question_num_votes_past_week'], 1)
示例4: ask
def ask(request):
ask_form = AskQuestion(request.POST or None)
args = {}
args['form'] = ask_form
if request.POST and ask_form.is_valid():
question = Question(text=ask_form.cleaned_data['text'], title=ask_form.cleaned_data['title'])
tags = ask_form.cleaned_data['tags']
g = Tag.objects.all()
getTag = tags.split(', ')
for tag in getTag:
counter = 0
for l in g:
if l.tag == tag:
counter += 1
if counter == 0:
t = Tag(tag=tag)
t.save()
user = auth.get_user(request)
question.author = user
question.save()
a = g.filter(tag__in=getTag)
question.tags.add(*a)
return redirect('questionGet', question_id=question.id)
else:
return render(request, 'ask.html', args)
示例5: gradeQuestion
def gradeQuestion(request):
questionList = json.loads(request.POST['questions'])
for question in questionList:
sentenceText = question['sentence']
questionText = question['question']
labelText = question['label']
gradeVal = question['grade']
if Sentence.objects.filter(text=sentenceText).exists() :
sentence = Sentence.objects.get(text=sentenceText)
else:
sentence = Sentence(text=sentenceText)
sentence.save()
if Question.objects.filter(text=questionText).exists():
question = Question.objects.get(text=questionText)
else:
question = Question(text=questionText)
question.save()
if Label.objects.filter(text=labelText).exists():
label = Label.objects.get(text = labelText)
else:
label = Label(text = labelText)
label.save()
grade = Grade(sentence=sentence,question=question,label=label,grade=gradeVal)
grade.save()
return HttpResponse('200')
示例6: auto_lock_old_questions
def auto_lock_old_questions():
"""Locks all questions that were created over 180 days ago"""
# Set up logging so it doesn't send Ricky email.
logging.basicConfig(level=logging.ERROR)
# Get a list of ids of questions we're going to go change. We need
# a list of ids so that we can feed it to the update, but then
# also know what we need to update in the index.
days_180 = datetime.now() - timedelta(days=180)
q_ids = list(Question.objects.filter(is_locked=False)
.filter(created__lte=days_180)
.values_list('id', flat=True))
if q_ids:
log.info('Updating %d questions', len(q_ids))
sql = """
UPDATE questions_question
SET is_locked = 1
WHERE id IN (%s)
""" % ','.join(map(str, q_ids))
cursor = connection.cursor()
cursor.execute(sql)
transaction.commit_unless_managed()
if settings.ES_LIVE_INDEXING:
try:
es = get_es()
# So... the first time this runs, it'll handle 160K
# questions or so which stresses everything. Thus we
# do it in chunks because otherwise this won't work.
#
# After we've done this for the first time, we can nix
# the chunking code.
from search.utils import chunked
for chunk in chunked(q_ids, 1000):
# Fetch all the documents we need to update.
es_docs = get_documents(Question, chunk)
log.info('Updating %d index documents', len(es_docs))
# For each document, update the data and stick it
# back in the index.
for doc in es_docs:
doc[u'question_is_locked'] = True
Question.index(doc, bulk=True, es=es)
es.flush_bulk(forced=True)
es.refresh(WRITE_INDEX, timesleep=0)
except ES_EXCEPTIONS:
# Something happened with ES, so let's push index updating
# into an index_task which retries when it fails because
# of ES issues.
index_task.delay(Question, q_ids)
示例7: test_question_no_answers_deleted
def test_question_no_answers_deleted(self):
q = question(title=u'Does this work?', save=True)
self.refresh()
eq_(Question.search().query('work').count(), 1)
q.delete()
self.refresh()
eq_(Question.search().query('work').count(), 0)
示例8: test_is_recent_with_recent_question
def test_is_recent_with_recent_question(self):
"""
is_recent() should return True for
questions whose pub_date is within the last day
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.is_recent(), True)
示例9: test_is_recent_with_future_question
def test_is_recent_with_future_question(self):
"""
is_recent() should return False for questions whose
pub_date is in the future
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertEqual(future_question.is_recent(),False)
示例10: test_from_invalid_url
def test_from_invalid_url(self):
"""Verify question returned from valid URL."""
q = question(save=True)
eq_(None, Question.from_url('/en-US/questions/%s/edit' % q.id))
eq_(None, Question.from_url('/en-US/kb/%s' % q.id))
eq_(None, Question.from_url('/random/url'))
eq_(None, Question.from_url('/en-US/questions/stats'))
示例11: test_notification_created
def test_notification_created(self):
"""Creating a new question auto-watches it for answers."""
u = User.objects.get(pk=118533)
q = Question(creator=u, title='foo', content='bar')
q.save()
assert QuestionReplyEvent.is_notifying(u, q)
示例12: test_is_recent_with_old_questions
def test_is_recent_with_old_questions(self):
"""
is_recent() should return False for questions
whose pub_date is older than 1 day
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.is_recent(), False)
示例13: test_notification_created
def test_notification_created(self):
"""Creating a new question auto-watches it."""
u = User.objects.get(pk=118533)
q = Question(creator=u, title='foo', content='bar')
q.save()
assert check_watch(Question, q.id, u.email, 'reply')
示例14: update_question_vote_chunk
def update_question_vote_chunk(data):
"""Update num_votes_past_week for a number of questions."""
# First we recalculate num_votes_past_week in the db.
log.info('Calculating past week votes for %s questions.' % len(data))
ids = ','.join(map(str, data))
sql = """
UPDATE questions_question q
SET num_votes_past_week = (
SELECT COUNT(created)
FROM questions_questionvote qv
WHERE qv.question_id = q.id
AND qv.created >= DATE(SUBDATE(NOW(), 7))
)
WHERE q.id IN (%s);
""" % ids
cursor = connection.cursor()
cursor.execute(sql)
transaction.commit_unless_managed()
# Next we update our index with the changes we made directly in
# the db.
if data and settings.ES_LIVE_INDEXING:
# Get the data we just updated from the database.
sql = """
SELECT id, num_votes_past_week
FROM questions_question
WHERE id in (%s);
""" % ids
cursor = connection.cursor()
cursor.execute(sql)
# Since this returns (id, num_votes_past_week) tuples, we can
# convert that directly to a dict.
id_to_num = dict(cursor.fetchall())
try:
# Fetch all the documents we need to update.
from questions.models import Question
from search import es_utils
es_docs = es_utils.get_documents(Question, data)
# For each document, update the data and stick it back in the
# index.
for doc in es_docs:
# Note: Need to keep this in sync with
# Question.extract_document.
num = id_to_num[int(doc[u'id'])]
doc[u'question_num_votes_past_week'] = num
Question.index(doc)
except ES_EXCEPTIONS:
# Something happened with ES, so let's push index updating
# into an index_task which retries when it fails because
# of ES issues.
index_task.delay(Question, id_to_num.keys())
示例15: setUp
def setUp(self):
super(TestQuestionMetadata, self).setUp()
# add a new Question to test with
question = Question(title='Test Question',
content='Lorem Ipsum Dolor',
creator_id=1)
question.save()
self.question = question