def test_accessibility_PhotosPage(self): photos_page = self.client.get(reverse('app_files:photos')) self.assertEqual(photos_page.status_code, 200) self.assertEqual(photos_page.context['title_page'], 'Photos') translation.activate('ru') self.assertEqual(photos_page.context['title_page'], 'Фото') self.assertTemplateUsed('app_files/photos.html')
def render_page(request, language, page, template_name=None, preview=None, args=None): """ Renders a page in the given language. A template_name can be given to override the default page template. A PageContent object can be passed as a preview. """ if not Page.objects.root().published(request.user) or \ not page.published(request.user) or \ page.requires_login and \ not request.user.is_authenticated(): raise Http404 # Make translations using Django's i18n work translation.activate(language) request.LANGUAGE_CODE = translation.get_language() # Initialize content/title dicts. content_dict = PositionDict(POSITIONS[0][0]) title_dict = PositionDict(POSITIONS[0][0]) context = get_page_context(request, language, page) # Call a custom context function for this page, if it exists. if page.context: try: func = resolve_dotted_path(page.context) except (ImportError, AttributeError, ValueError), e: raise StandardError, 'The context function for this page does not exist. %s: %s' % (e.__class__.__name__, e) if args: response = func(request, context, args) else: response = func(request, context) if response: return response
def process_response(self, request, response): # First set the default language, this will be used if there is none # in the path default_language = getattr(request, 'default_language', '') if default_language: translation.activate(default_language) language = translation.get_language() if (response.status_code == 404 and not translation.get_language_from_path(request.path_info) and self.is_language_prefix_patterns_used(request)): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) if settings.APPEND_SLASH and not language_path.endswith('/'): language_path += '/' if is_valid_path(language_path, urlconf): language_url = "%s://%s/%s%s" % ( request.is_secure() and 'https' or 'http', request.get_host(), language, request.get_full_path()) return HttpResponseRedirect(language_url) translation.deactivate() patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def test_accessibility_VideosPage(self): videos_page = self.client.get(reverse('app_files:videos')) self.assertEqual(videos_page.status_code, 200) self.assertEqual(videos_page.context['title_page'], 'Videos') translation.activate('ru') self.assertEqual(videos_page.context['title_page'], 'Видео') self.assertTemplateUsed('app_files/videos.html')
def translate_url(context, language): resolver_match = context['request'].resolver_match request_language = translation.get_language() translation.activate(language) url = reverse(resolver_match.url_name, args=resolver_match.args, kwargs=resolver_match.kwargs) translation.activate(request_language) return url
def get_success_url(self): front_path = reverse('frontpage', kwargs={'region': self.object.slug}) # Send them to the subdomain appropriate for the language, # in order to avoid the redirect. If we wait for the language # redirect here, then the messages cookie could get set on the # base domain, and then never cleared when viewed on the # language subdomain. region_lang = self._default_language request_lang = getattr(self.request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE) translation.activate(region_lang) self.request.LANGUAGE_CODE = region_lang if request_lang != region_lang: host = self.request.get_host().split('.') # We keep the language code in the subdomain, unless we're on the default language. if request_lang == settings.LANGUAGE_CODE: base_hostname = '.'.join(host) else: base_hostname = '.'.join(host[1:]) if region_lang != settings.LANGUAGE_CODE: domain = '%s.%s' % (region_lang, base_hostname) else: domain = base_hostname return '%s://%s%s' % ( self.request.is_secure() and 'https' or 'http', domain, front_path ) return front_path
def handle(self, *args, **options): log_file = args[-1] period_name = args[-2] logger = Logger(log_file) logger.logger.info('########### Processing #############') period = Period.objects.get(name=period_name) users = User.objects.filter(username=self.username) translation.activate(self.language_code) for user in users: profile, c = Profile.objects.get_or_create(user=user) students = user.student.all() if students: student = students[0] else: student = Student() professors = user.professor.all() quotas = user.quotas.all() if student.period == period or professors or quotas: if profile and user.is_active: if not profile.init_password and user.email: self.init_password_email(user) profile.init_password = True profile.save() logger.logger.info('init : ' + user.username) logger.logger.info('############## Done #################')
def inner_run(): from django.conf import settings from django.utils import translation print "Validating models..." self.validate(display_num_errors=True) print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE) print "Development server is running at http://%s:%s/" % (addr, port) print "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = AdminMediaHandler(WSGIHandler(), admin_media_path) run(addr, int(port), handler) except WSGIServerException, e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", 98: "That port is already in use.", 99: "That IP address can't be assigned-to.", } try: error_text = ERRORS[e.args[0].args[0]] except (AttributeError, KeyError): error_text = str(e) sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1)
def process_request(self, request): print(request.META.get('HTTP_X_FORWARDED_HOST', '')) try: lang = request.META['HTTP_X_FORWARDED_HOST'].split("glamfame.")[1].split("/")[0] if lang == "ru": lang = "ru" settings.DATABASES['default']['NAME'] = 'glamazerru' settings.ELASTIC_SEARCH_URL = 'http://127.0.0.1:9201/' settings.HAYSTACK_CONNECTIONS["default"]["URL"] = settings.ELASTIC_SEARCH_URL settings.MEDIA_FOLDER = 'media_ru' elif lang == "com": lang = "en" settings.DATABASES['default']['NAME'] = 'glamazer' settings.ELASTIC_SEARCH_URL = 'http://127.0.0.1:9200/' settings.HAYSTACK_CONNECTIONS["default"]["URL"] = settings.ELASTIC_SEARCH_URL settings.MEDIA_FOLDER = 'media' request.session['django_language'] = lang translation.activate(lang) except: try: lang = request.META['HTTP_HOST'].split(":")[1].split("/")[0] except: lang = "8000" if lang == "8000": lang = "en" request.session['django_language'] = lang translation.activate(lang) settings.__LANG = "EN"
def translation_set_language(request, select_language): """ Set and activate a language, if that language is available. """ if translation.check_for_language(select_language): fallback = False else: # The page is in a language that Django has no messages for. # We display anyhow, but fall back to primary language for # other messages and other applications. It is *highly* recommended to # create a new django.po for the language instead of # using this behaviour. select_language = django_settings.LANGUAGES[0][0] fallback = True translation.activate(select_language) request.LANGUAGE_CODE = translation.get_language() if hasattr(request, 'session'): # User has a session, then set this language there if select_language != request.session.get('django_language'): request.session['django_language'] = select_language elif request.method == 'GET' and not fallback: # No session is active. We need to set a cookie for the language # so that it persists when the user changes his location to somewhere # not under the control of the CMS. # Only do this when request method is GET (mainly, do not abort # POST requests) response = HttpResponseRedirect(request.get_full_path()) response.set_cookie(django_settings.LANGUAGE_COOKIE_NAME, select_language) return response
def get(self, request, *args, **kwargs): object_list = self.get_queryset() if not can_download_changes(request.user, self.project): raise PermissionDenied() # Always output in english activate('en') response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=changes.csv' writer = csv.writer(response) # Add header writer.writerow(('timestamp', 'action', 'user', 'url')) for change in object_list[:2000].iterator(): writer.writerow(( change.timestamp.isoformat(), change.get_action_display().encode('utf8'), change.user.username.encode('utf8') if change.user else '', change.get_absolute_url(), )) return response
def run(self, submission, template_code): logger.info('SendEmailFromTemplate:%d template %s' % ( submission.id, template_code )) try: translation.activate(submission.submission_language) letter = LetterTemplate.objects.language().get(code=template_code) email = EmailMessage( letter.subject, letter.text % {'name': submission.applicant}, '*****@*****.**', [submission.applicant_email], list(settings.MAIL_BCC_LIST), headers = {'Reply-To': '*****@*****.**'} ) email.send() except: logger.info('SendEmailFromTemplate:%d template %s exception' % ( submission.id, template_code )) raise finally: translation.deactivate() logger.info('SendEmailFromTemplate:%d template %s done' % ( submission.id, template_code ))
def send_email(user, workout, delta): ''' Notify a user that a workout is about to expire :type user User :type workout Workout :type delta datetime.timedelta ''' # Update the last notification date field user.userprofile.last_workout_notification = datetime.date.today() user.userprofile.save() # Compose and send the email translation.activate(user.userprofile.notification_language.short_name) context = {} context['site'] = Site.objects.get_current() context['workout'] = workout context['expired'] = True if delta.days < 0 else False context['days'] = abs(delta.days) subject = _('Workout will expire soon') message = loader.render_to_string('workout/email_reminder.tpl', context) mail.send_mail(subject, message, EMAIL_FROM, [user.email], fail_silently=True)
def _apply_changes(request, old_status, new_status): """Apply the form changes""" if old_status['hostname'] != new_status['hostname']: try: set_hostname(new_status['hostname']) except Exception as exception: messages.error(request, _('Error setting hostname: {exception}') .format(exception=exception)) else: messages.success(request, _('Hostname set')) if old_status['domainname'] != new_status['domainname']: try: set_domainname(new_status['domainname']) except Exception as exception: messages.error(request, _('Error setting domain name: {exception}') .format(exception=exception)) else: messages.success(request, _('Domain name set')) if old_status['language'] != new_status['language']: language = new_status['language'] try: translation.activate(language) request.session[translation.LANGUAGE_SESSION_KEY] = language except Exception as exception: messages.error(request, _('Error setting language: {exception}') .format(exception=exception)) else: messages.success(request, _('Language changed'))
def run(self, submission): logger.info('SendSubmissionEmail for submission %s' % ( submission.id )) try: translation.activate(submission.submission_language) email = EmailMessage( 'Cinema Perpetuum Mobile 2013', self.get_email_message(submission), '*****@*****.**', [submission.applicant_email], list(settings.MAIL_BCC_LIST), headers = {'Reply-To': '*****@*****.**'}) email.attach( 'cpm2013.pdf', self.create_pdf(submission), 'application/pdf' ) email.send() except: logger.exception('') raise finally: translation.deactivate() try: submission = Submission.objects.get(pk=submission.pk) except Submission.DoesNotExist: logger.exception('Failed to update "email sent" status') else: submission.comment_email_sent = True submission.save()
def test_string_with_newlines_translation(self): translation.activate("fr") res = I18nPreprocessor().process( "<div>{{# _ }}Hello, \n{{name}}\n!{{/ _ }} {{# _ }}Second string{{/ _ }}</div>" ) self.assertEqual(res, "<div>XXX Hello, \n{{name}}\n! XXX Second string</div>")
def process_request(self, request): domain = get_domain() host = request.get_host() user = request.user lang = get_language_key(host, domain, user) translation.activate(lang) request.LANGUAGE_CODE = translation.get_language()
def change_lang(context, lang=None, *args, **kwargs): current_language = get_language() if 'request' in context and lang and current_language: request = context['request'] match = resolve(request.path) non_prefixed_path = re.sub(current_language + '/', '', request.path, count=1) # means that is an wagtail page object if match.url_name == 'wagtail_serve': path_components = [component for component in non_prefixed_path.split('/') if component] page, args, kwargs = request.site.root_page.specific.route(request, path_components) activate(lang) translated_url = page.url activate(current_language) return translated_url elif match.url_name == 'wagtailsearch_search': path_components = [component for component in non_prefixed_path.split('/') if component] translated_url = '/' + lang + '/' + path_components[0] + '/' if request.GET: translated_url += '?' for key, value in iteritems(request.GET): translated_url += key + '=' + value return translated_url return ''
def test_pl_po_manually(self): lang = settings.LANGUAGE_CODE invalidate_language("pl") self.assertEqual(Translation.objects.count(), 0) MasterTranslation.objects.create( language_code=lang, text="%(n)s result", plural_text="%(n)s results", ) MasterTranslation.objects.create( language_code=lang, text="cat", ) mock_file_contents = u'''# Something something # Translators list msgid "" msgstr "" "Project-Id-Version: django\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2015-01-17 11:07+0100\n" "PO-Revision-Date: 2015-01-18 15:19+0000\n" "Last-Translator: Janusz Harkot <*****@*****.**>\n" "Language-Team: Polish (http://www.transifex.com/projects/p/django/language/" "pl/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: pl\n" "Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " "|| n%100>=20) ? 1 : 2);\n" #, python-format msgid "%(n)s result" msgid_plural "%(n)s results" msgstr[0] "%(n)s wynik" msgstr[1] "%(n)s wyniki" msgstr[2] "%(n)s wyników" #, python-format msgid "cat" msgstr "kot" ''' #msgctxt "context hint" import_translations_from_po(mock_file_contents, "pl", lang) translation.activate("pl") self.assertEqual(ngettext("%(n)s result", "", 0).decode('utf-8'), u"%(n)s wyników") self.assertEqual(ngettext("%(n)s result", "", 1).decode('utf-8'), u"%(n)s wynik") self.assertEqual(ngettext("%(n)s result", "", 2).decode('utf-8'), u"%(n)s wyniki") self.assertEqual(ngettext("%(n)s result", "", 5).decode('utf-8'), u"%(n)s wyników") # Singlar translation test self.assertEqual(gettext("cat"), u"kot") # This form is wrong because po don't support the fraction plural form! self.assertEqual(ngettext("%(n)s result", "", 0.5).decode('utf-8'), u"%(n)s wyników") # u") self.assertEqual(get_plural_index("pl", 0), cldr.MANY) self.assertEqual(get_plural_index("pl", 1), cldr.ONE) self.assertEqual(get_plural_index("pl", 2), cldr.FEW) self.assertEqual(get_plural_index("pl", 5), cldr.MANY) self.assertEqual(get_plural_index("pl", 1.1), cldr.OTHER)
def test_internationalization(self): for lang, h1_text in [('en', 'Welcome to TaskBuster!'), ('ca', 'Benvingut a TaskBuster!')]: activate(lang) self.browser.get(self.get_full_url("home")) h1 = self.browser.find_element_by_tag_name("h1") self.assertEqual(h1.text, h1_text)
def activate(self, locale=None): """Active a locale.""" old_locale = translation.get_language() if locale: translation.activate(locale) yield translation.activate(old_locale)
def logout(request): """View: deletes visitor from session, displays farewell message.""" langues = [list(i)+[0] for i in LISTE_LANGUES] lang = request.GET.get('lang',None) if lang: request.session['django_language'] = lang activate(lang) else: lang = get_language() for l in langues: if lang==l[0]: l[2]=1 try: del request.session['v'] # del request.session['django_language'] except KeyError: pass msg = _('You have been logged out. Thanks for visiting us today. <br /><a href="/login/">New login</a>') return render_to_response('msg.html', {'msg': msg, 'langues': langues, })
def set_lang(request, lang_code): from django.utils import translation translation.activate(lang_code) response = redirect(request.META['HTTP_REFERER']) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response
def get_frontend_order_state(contact, valid_lines=True): """ Get a dict structure mirroring what the frontend JavaScript would submit. :type contact: Contact|None """ translation.activate("en") shop = get_default_shop() tax = Tax.objects.create(code="test_code", rate=decimal.Decimal("0.20"), name="Default") tax_class = TaxClass.objects.create(identifier="test_tax_class", name="Default") rule = TaxRule.objects.create(tax=tax) rule.tax_classes.add(tax_class) rule.save() product = create_product( sku=printable_gibberish(), supplier=get_default_supplier(), shop=shop ) product.tax_class = tax_class product.save() if valid_lines: lines = [ {"id": "x", "type": "product", "product": {"id": product.id}, "quantity": "32", "baseUnitPrice": 50}, {"id": "y", "type": "other", "sku": "hello", "text": "A greeting", "quantity": 1, "unitPrice": "5.5"}, {"id": "z", "type": "text", "text": "This was an order!", "quantity": 0}, ] else: unshopped_product = create_product(sku=printable_gibberish(), supplier=get_default_supplier()) not_visible_product = create_product( sku=printable_gibberish(), supplier=get_default_supplier(), shop=shop ) not_visible_shop_product = not_visible_product.get_shop_instance(shop) not_visible_shop_product.visible = False not_visible_shop_product.save() lines = [ {"id": "x", "type": "product"}, # no product? {"id": "x", "type": "product", "product": {"id": unshopped_product.id}}, # not in this shop? {"id": "y", "type": "product", "product": {"id": -product.id}}, # invalid product? {"id": "z", "type": "other", "quantity": 1, "unitPrice": "q"}, # what's that price? {"id": "rr", "type": "product", "quantity": 1, "product": {"id": not_visible_product.id}} # not visible ] state = { "customer": {"id": contact.id if contact else None}, "lines": lines, "methods": { "shippingMethod": {"id": get_default_shipping_method().id}, "paymentMethod": {"id": get_default_payment_method().id}, }, "shop": { "selected": { "id": shop.id, "name": shop.name, "currency": shop.currency, "priceIncludeTaxes": shop.prices_include_tax } } } return state
def test_page_slug_has_correct_lang(self): """ Test that slug generation is done for the default language and not the active one. """ from collections import OrderedDict from django.utils.translation import get_language, activate from mezzanine.utils.urls import slugify default_language = get_language() code_list = OrderedDict(settings.LANGUAGES) del code_list[default_language] title_1 = "Title firt language" title_2 = "Title second language" page, _ = RichTextPage.objects.get_or_create(title=title_1) for code in code_list: try: activate(code) except: pass else: break # No valid language found page.delete() return page.title = title_2 page.save() self.assertEqual(page.get_slug(), slugify(title_1)) self.assertEqual(page.title, title_2) activate(default_language) self.assertEqual(page.title, title_1) page.delete()
def detail(request, slug, template_name="news/detail.html", template_name_ajax="news/detail_ajax.html"): """ News item detail. In the template, we show the title and the body of the News item and links to all its' all available translations. :param django.http.HttpRequest request: :param string slug: Foo item slug. :param string template_name: :return django.http.HttpResponse: """ layout = get_layout(as_instance=True) language = get_language_from_request(request) if language is not None: translation.activate(language) results_kwargs = {"slug": slug} try: queryset = NewsItem._default_manager.filter(**results_kwargs) item = queryset.get(**results_kwargs) except Exception as e: raise Http404 context = {"layout": layout, "item": item} if request.is_ajax(): template_name = template_name_ajax return render_to_response(template_name, context, context_instance=RequestContext(request))
def notify_topic_subscribers(post): topic = post.topic if post != topic.head: for user in topic.subscribers.all(): if user != post.user: try: email_validator.clean(user.email) except: #invalid email continue old_lang = translation.get_language() lang = user.profile.language or dict(settings.LANGUAGES)[settings.LANGUAGE_CODE.split('-')[0]] translation.activate(lang) delete_url = reverse('pybb:delete_subscription', args=[post.topic.id]) current_site = Site.objects.get_current() subject = render_to_string('pybb/mail_templates/subscription_email_subject.html', { 'site': current_site, 'post': post }) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('pybb/mail_templates/subscription_email_body.html', { 'site': current_site, 'post': post, 'delete_url': delete_url, }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=True) translation.activate(old_lang)
def test_middleware(self): def set_cache(request, lang, msg): translation.activate(lang) response = HttpResponse() response.content= msg return UpdateCacheMiddleware().process_response(request, response) settings.CACHE_MIDDLEWARE_SECONDS = 60 settings.CACHE_MIDDLEWARE_KEY_PREFIX="test" settings.CACHE_BACKEND='locmem:///' settings.USE_I18N = True en_message ="Hello world!" es_message ="Hola mundo!" request = self._get_request_cache() set_cache(request, 'en', en_message) get_cache_data = FetchFromCacheMiddleware().process_request(request) # Check that we can recover the cache self.assertNotEqual(get_cache_data.content, None) self.assertEqual(en_message, get_cache_data.content) # change the session language and set content request = self._get_request_cache() set_cache(request, 'es', es_message) # change again the language translation.activate('en') # retrieve the content from cache get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data.content, en_message) # change again the language translation.activate('es') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data.content, es_message)
def test_protected_fields(): activate("en") shop = Shop.objects.create( name="testshop", identifier="testshop", status=ShopStatus.ENABLED, public_name="test shop", domain="derp", currency="EUR" ) get_currency("EUR") get_currency("USD") assert shop.name == "testshop" assert shop.currency == "EUR" assert not ConfigurationItem.objects.filter(shop=shop, key="languages").exists() shop_form = ShopBaseForm(instance=shop, languages=settings.LANGUAGES) assert not shop_form._get_protected_fields() # No protected fields just yet, right? data = get_form_data(shop_form, prepared=True) shop_form = ShopBaseForm(data=data, instance=shop, languages=settings.LANGUAGES) _test_cleanliness(shop_form) shop_form.save() # Now let's make it protected! create_product(printable_gibberish(), shop=shop, supplier=get_default_supplier()) order = create_random_order(customer=create_random_person(), shop=shop) assert order.shop == shop # And try again... data["currency"] = "USD" shop_form = ShopBaseForm(data=data, instance=shop, languages=settings.LANGUAGES) assert shop_form._get_protected_fields() # So protected! _test_cleanliness(shop_form) shop = shop_form.save() assert shop.currency == "EUR" # But the shop form ignored the change . . .
def profile_edit(request): profile = request.user.get_profile() if request.method == 'POST': form = forms.ProfileEditForm(request.POST, request.FILES, instance=profile) if form.is_valid(): olang = get_language() activate(profile.preflang) messages.success(request, _('Profile updated')) form.save() next = reverse('users_profile_edit') next = force_language_in_url(next, olang, profile.preflang) return http.HttpResponseRedirect(next) else: messages.error(request, _('There were problems updating your ' 'profile. Please correct the problems ' 'and submit again.')) else: form = forms.ProfileEditForm(instance=profile) return render_to_response('users/profile_edit_main.html', { 'profile': profile, 'profile_form': form, 'general_tab': True, }, context_instance=RequestContext(request))
def __enter__(self): self.oldlang = get_language() activate(self.newlang)
def process_request(self, request): language = self.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = language
def home_real(request: HttpRequest) -> HttpResponse: # We need to modify the session object every two weeks or it will expire. # This line makes reloading the page a sufficient action to keep the # session alive. request.session.modified = True user_profile = request.user # If a user hasn't signed the current Terms of Service, send them there if settings.TERMS_OF_SERVICE is not None and settings.TOS_VERSION is not None and \ int(settings.TOS_VERSION.split('.')[0]) > user_profile.major_tos_version(): return accounts_accept_terms(request) narrow = [] # type: List[List[Text]] narrow_stream = None narrow_topic = request.GET.get("topic") if request.GET.get("stream"): try: narrow_stream_name = request.GET.get("stream") (narrow_stream, ignored_rec, ignored_sub) = access_stream_by_name(user_profile, narrow_stream_name) narrow = [["stream", narrow_stream.name]] except Exception: logging.exception("Narrow parsing") if narrow_stream is not None and narrow_topic is not None: narrow.append(["topic", narrow_topic]) register_ret = do_events_register(user_profile, request.client, apply_markdown=True, client_gravatar=True, narrow=narrow) user_has_messages = (register_ret['max_message_id'] != -1) # Reset our don't-spam-users-with-email counter since the # user has since logged in if user_profile.last_reminder is not None: # nocoverage # TODO: Look into the history of last_reminder; we may have # eliminated that as a useful concept for non-bot users. user_profile.last_reminder = None user_profile.save(update_fields=["last_reminder"]) # Brand new users get narrowed to PM with welcome-bot needs_tutorial = user_profile.tutorial_status == UserProfile.TUTORIAL_WAITING first_in_realm = realm_user_count(user_profile.realm) == 1 # If you are the only person in the realm and you didn't invite # anyone, we'll continue to encourage you to do so on the frontend. prompt_for_invites = first_in_realm and \ not PreregistrationUser.objects.filter(referred_by=user_profile).count() if user_profile.pointer == -1 and user_has_messages: # Put the new user's pointer at the bottom # # This improves performance, because we limit backfilling of messages # before the pointer. It's also likely that someone joining an # organization is interested in recent messages more than the very # first messages on the system. register_ret['pointer'] = register_ret['max_message_id'] user_profile.last_pointer_updater = request.session.session_key if user_profile.pointer == -1: latest_read = None else: try: latest_read = UserMessage.objects.get( user_profile=user_profile, message__id=user_profile.pointer) except UserMessage.DoesNotExist: # Don't completely fail if your saved pointer ID is invalid logging.warning("%s has invalid pointer %s" % (user_profile.email, user_profile.pointer)) latest_read = None # Set default language and make it persist default_language = register_ret['default_language'] url_lang = '/{}'.format(request.LANGUAGE_CODE) if not request.path.startswith(url_lang): translation.activate(default_language) request.session[ translation.LANGUAGE_SESSION_KEY] = translation.get_language() # Pass parameters to the client-side JavaScript code. # These end up in a global JavaScript Object named 'page_params'. page_params = dict( # Server settings. development_environment=settings.DEVELOPMENT, debug_mode=settings.DEBUG, test_suite=settings.TEST_SUITE, poll_timeout=settings.POLL_TIMEOUT, login_page=settings.HOME_NOT_LOGGED_IN, root_domain_uri=settings.ROOT_DOMAIN_URI, maxfilesize=settings.MAX_FILE_UPLOAD_SIZE, max_avatar_file_size=settings.MAX_AVATAR_FILE_SIZE, server_generation=settings.SERVER_GENERATION, use_websockets=settings.USE_WEBSOCKETS, save_stacktraces=settings.SAVE_FRONTEND_STACKTRACES, warn_no_email=settings.WARN_NO_EMAIL, server_inline_image_preview=settings.INLINE_IMAGE_PREVIEW, server_inline_url_embed_preview=settings.INLINE_URL_EMBED_PREVIEW, password_min_length=settings.PASSWORD_MIN_LENGTH, password_min_guesses=settings.PASSWORD_MIN_GUESSES, jitsi_server_url=settings.JITSI_SERVER_URL, # Misc. extra data. have_initial_messages=user_has_messages, initial_servertime=time.time( ), # Used for calculating relative presence age default_language_name=get_language_name( register_ret['default_language']), language_list_dbl_col=get_language_list_for_templates( register_ret['default_language']), language_list=get_language_list(), needs_tutorial=needs_tutorial, first_in_realm=first_in_realm, prompt_for_invites=prompt_for_invites, furthest_read_time=sent_time_in_epoch_seconds(latest_read), has_mobile_devices=num_push_devices_for_user(user_profile) > 0, bot_types=get_bot_types(user_profile), ) undesired_register_ret_fields = [ 'streams', ] for field_name in set( register_ret.keys()) - set(undesired_register_ret_fields): page_params[field_name] = register_ret[field_name] if narrow_stream is not None: # In narrow_stream context, initial pointer is just latest message recipient = get_stream_recipient(narrow_stream.id) try: initial_pointer = Message.objects.filter( recipient=recipient).order_by('id').reverse()[0].id except IndexError: initial_pointer = -1 page_params["narrow_stream"] = narrow_stream.name if narrow_topic is not None: page_params["narrow_topic"] = narrow_topic page_params["narrow"] = [ dict(operator=term[0], operand=term[1]) for term in narrow ] page_params["max_message_id"] = initial_pointer page_params["pointer"] = initial_pointer page_params["have_initial_messages"] = (initial_pointer != -1) page_params["enable_desktop_notifications"] = False statsd.incr('views.home') show_invites = True # Some realms only allow admins to invite users if user_profile.realm.invite_by_admins_only and not user_profile.is_realm_admin: show_invites = False request._log_data['extra'] = "[%s]" % (register_ret["queue_id"], ) response = render( request, 'zerver/index.html', context={ 'user_profile': user_profile, 'page_params': JSONEncoderForHTML().encode(page_params), 'nofontface': is_buggy_ua(request.META.get("HTTP_USER_AGENT", "Unspecified")), 'avatar_url': avatar_url(user_profile), 'show_debug': settings.DEBUG and ('show_debug' in request.GET), 'pipeline': settings.PIPELINE_ENABLED, 'show_invites': show_invites, 'is_admin': user_profile.is_realm_admin, 'show_webathena': user_profile.realm.webathena_enabled, 'enable_feedback': settings.ENABLE_FEEDBACK, 'embedded': narrow_stream is not None, }, ) patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True) return response
def handle_noargs(self, **options): self.verbosity = int(options.get("verbosity", 1)) self.interactive = options.get("interactive") # post a bunch of answers by admin now - that active_question is # posted by someone else if self.interactive: answer = choice_dialog( "This command will DELETE ALL DATA in the current database, and will fill the database with test data. Are you absolutely sure you want to proceed?", choices=( "yes", "no", )) if answer != "yes": return translation.activate(django_settings.LANGUAGE_CODE) self.backup_settings() self.modify_settings() # saves time on running the command # Create Users users = self.create_users() # Create a bunch of questions and answers by a single user # to test pagination in the user profile active_question = self.create_questions(users[0:1]) # Create Questions, vote for questions by all other users active_question = self.create_questions(users) active_answer = self.create_answers(users[0:1], active_question) # Create Answers, vote for the answers, vote for the active question # vote for the active answer active_answer = self.create_answers(users, active_question) # Create Comments, vote for the active answer active_question_comment, active_answer_comment = self.create_comments( users, active_question, active_answer) # Edit the active question, answer and comments active_question.author.edit_question(question=active_question, title=TITLE_TEMPLATE % "EDITED", body_text=CONTENT_TEMPLATE, revision_comment="EDITED", force=True) self.print_if_verbose("User has edited the active question") active_answer.author.edit_answer(answer=active_answer, body_text=COMMENT_TEMPLATE, force=True) self.print_if_verbose("User has edited the active answer") active_answer_comment.author.edit_comment( comment_post=active_answer_comment, body_text=ANSWER_TEMPLATE) self.print_if_verbose("User has edited the active answer comment") active_question_comment.author.edit_comment( comment_post=active_question_comment, body_text=ANSWER_TEMPLATE) self.print_if_verbose("User has edited the active question comment") # Accept best answer active_question.author.accept_best_answer( answer=active_answer, force=True, ) self.print_if_verbose("User has accepted a best answer") self.restore_settings() self.print_if_verbose("DONE")
def test_translated_field_default_null(): assert Translation.objects.count() == 0 obj = TranslatedModelWithDefaultNull.objects.create(name='english name') def get_model(): return TranslatedModelWithDefaultNull.objects.get(pk=obj.pk) assert Translation.objects.count() == 1 # Make sure the translation id is stored on the model, not the autoid. assert obj.name.id == obj.name_id # Reload the object from database with a different locale activated. # Its name should still be there, using the fallback... translation.activate('de') german = get_model() assert german.name == 'english name' assert german.name.locale == 'en-us' # Check that a different locale creates a new row with the same id. german.name = u'Gemütlichkeit name' german.save() assert Translation.objects.count() == 2 # New name *and* description. assert german.name == u'Gemütlichkeit name' assert german.name.locale == 'de' # ids should be the same, autoids are different. assert obj.name.id == german.name.id assert obj.name.autoid != german.name.autoid # Check that de finds the right translation. fresh_german = get_model() assert fresh_german.name == u'Gemütlichkeit name' # Update! translation.activate('en-us') obj = TranslatedModelWithDefaultNull.objects.get(pk=obj.pk) translation_id = obj.name.autoid obj.name = 'new name' obj.save() obj = TranslatedModelWithDefaultNull.objects.get(pk=obj.pk) assert obj.name == 'new name' assert obj.name.locale == 'en-us' # Make sure it was an update, not an insert. assert obj.name.autoid == translation_id # Set translations with a dict. strings = {'en-us': 'right language', 'de': 'wrong language'} obj = TranslatedModelWithDefaultNull.objects.create(name=strings) # Make sure we get the English text since we're in en-US. assert obj.name == 'right language' # Check that de was set. translation.activate('de') obj = TranslatedModelWithDefaultNull.objects.get(pk=obj.pk) assert obj.name == 'wrong language' assert obj.name.locale == 'de'
def setUp(self): super(TranslationMultiDbTests, self).setUp() translation.activate('en-US')
def __exit__(self, type, value, traceback): activate(self.oldlang)
def preferences(request): if request.method == "POST": form = PreferencesForm(request.POST) form.user = request.user if form.is_valid(): try: newdata = form.cleaned_data request.user.language = newdata["language"] if "theme" in newdata: request.user.theme = newdata["theme"] request.user.pagesize = newdata["pagesize"] if newdata["cur_password"]: request.user.set_password(newdata["new_password1"]) # Updating the password logs out all other sessions for the user # except the current one if # django.contrib.auth.middleware.SessionAuthenticationMiddleware # is enabled. update_session_auth_hash(request, form.user) request.user.save() # Switch to the new theme and language immediately if "theme" in newdata: request.theme = newdata["theme"] if newdata["language"] == "auto": newdata[ "language"] = translation.get_language_from_request( request) if translation.get_language() != newdata["language"]: translation.activate(newdata["language"]) request.LANGUAGE_CODE = translation.get_language() messages.add_message( request, messages.INFO, force_text(_("Successfully updated preferences")), ) except Exception as e: logger.error("Failure updating preferences: %s" % e) messages.add_message( request, messages.ERROR, force_text(_("Failure updating preferences")), ) else: pref = request.user form = PreferencesForm({ "language": pref.language, "theme": pref.theme, "pagesize": pref.pagesize }) LANGUAGE = User.languageList[0][1] for l in User.languageList: if l[0] == request.user.language: LANGUAGE = l[1] return render( request, "common/preferences.html", context={ "title": _("My preferences"), "form": form, "THEMES": settings.THEMES, "LANGUAGE": LANGUAGE, }, )
def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self.browser.wait = WebDriverWait(self.browser, 10) print("hey") activate('en')
def inner_run(): from django.conf import settings from django.utils import translation print "Validating models..." self.validate(display_num_errors=True) print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE) print "Development server is running at http://%s:%s/" % (addr, port) print "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: # BEGIN profiling import cProfile import pstats import time, tempfile profile_temp_dir = None if profile_temp_dir is not None: tempfile.tempdir = profile_temp_dir def make_profiler_handler(inner_handler): def handler(environ, start_response): print "============= Starting response ====================" path = environ['PATH_INFO'] if path.startswith(settings.MEDIA_URL): return inner_handler(environ, start_response) path = path.strip('/').replace('/', '.') if path: prefix = 'p.%s.%3f' % (path, time.time()) else: prefix = 'p.%3f' % time.time() fd, profname = tempfile.mkstemp('.prof', prefix) os.close(fd) prof = cProfile.Profile() try: return prof.runcall(inner_handler, environ, start_response) finally: prof.dump_stats(profname) stats = pstats.Stats(profname) stats.sort_stats('cumulative', 'time', 'calls') stats.print_stats('lingcod',20) print " * Complete cProfile output at %s" % profname print "============= Done =================================" return handler # END #handler = AdminMediaHandler(WSGIHandler(), admin_media_path) handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), admin_media_path)) run(addr, int(port), handler) except WSGIServerException, e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", 98: "That port is already in use.", 99: "That IP address can't be assigned-to.", } try: error_text = ERRORS[e.args[0].args[0]] except (AttributeError, KeyError): error_text = str(e) sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1)
def test_uses_index_template(self): activate('en') response = self.client.get(reverse("home")) self.assertTemplateUsed(response, "taskbuster/index.html")
def dispatch(self, *args, **kwargs): lang = self.request.GET.get('lang') if lang: translation.activate(lang) self.request.LANGUAGE_CODE = lang return super(TrekDetail, self).dispatch(*args, **kwargs)
def _fixture_setup(self): super(BaseCMSTestCase, self)._fixture_setup() self.create_fixtures() activate("en")
# The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = wp4_version_string # The full version, including alpha/beta/rc tags. release = wp4_version_string # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en_GB' # Not using en_DB as the rest of the locale doesn't recognise that activate(language) # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None
def django_init(self): """ Checks for the required data and initializes the application. """ # manage.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", SETTINGS) # django.core.management.execute_from_command_line(argv=ARGS) """ A simple method that runs a ManagementUtility. """ from django.core.management import ManagementUtility utility = ManagementUtility(ARGS) # utility.execute() """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ from django.core.management import LaxOptionParser # For backwards compatibility: get_version() used to be in this module. from django import get_version from django.core.management.base import BaseCommand, handle_default_options # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = LaxOptionParser(usage="%prog subcommand [options] [args]", version=get_version(), option_list=BaseCommand.option_list) utility.autocomplete() try: options, args = parser.parse_args(utility.argv) handle_default_options(options) except: pass # Ignore any option errors at this point. subcommand = utility.argv[1] klass = utility.fetch_command(subcommand) # klass.run_from_argv(utility.argv) """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ from django.core.management.base import CommandError parser = klass.create_parser(utility.argv[0], utility.argv[1]) options, args = parser.parse_args(utility.argv[2:]) handle_default_options(options) options = options.__dict__ # klass.execute(*args, **options.__dict__) """ Try to execute this command, performing model validation if needed (as controlled by the attribute ``klass.requires_model_validation``, except if force-skipped). """ from django.core.management.base import OutputWrapper klass.stdout = OutputWrapper(options.get('stdout', sys.stdout)) klass.stderr = OutputWrapper(options.get('stderr', sys.stderr), klass.style.ERROR) #klass.can_import_settings = True from django.conf import settings saved_locale = None #klass.leave_locale_alone = False # Only mess with locales if we can assume we have a working # settings file, because django.utils.translation requires settings # (The final saying about whether the i18n machinery is active will be # found in the value of the USE_I18N setting) #klass.can_import_settings = True # Switch to US English, because django-admin.py creates database # content like permissions, and those shouldn't contain any # translations. from django.utils import translation saved_locale = translation.get_language() translation.activate('en-us') try: # Validation is called explicitly each time the server is reloaded. #klass.requires_model_validation = False addrport = args[0] print 'addrport %s' % addrport args = args[1:] # klass.handle(addrport='', *args, **options) import re from django.core.management.commands.runserver import naiveip_re, DEFAULT_PORT from django.conf import settings if not settings.DEBUG and not settings.ALLOWED_HOSTS: raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.') klass.use_ipv6 = options.get('use_ipv6') if klass.use_ipv6 and not socket.has_ipv6: raise CommandError('Your Python does not support IPv6.') if args: raise CommandError('Usage is runserver %s' % klass.args) klass._raw_ipv6 = False if not addrport: klass.addr = '' klass.port = DEFAULT_PORT else: m = re.match(naiveip_re, addrport) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % addrport) klass.addr, _ipv4, _ipv6, _fqdn, klass.port = m.groups() if not klass.port.isdigit(): raise CommandError("%r is not a valid port number." % klass.port) if klass.addr: if _ipv6: klass.addr = klass.addr[1:-1] klass.use_ipv6 = True klass._raw_ipv6 = True elif klass.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % klass.addr) if not klass.addr: klass.addr = '::1' if klass.use_ipv6 else '127.0.0.1' klass._raw_ipv6 = bool(klass.use_ipv6) # klass.run(*args, **options) """ Runs the server, using the autoreloader if needed """ #from django.utils import autoreload use_reloader = options.get('use_reloader') if use_reloader: # use queue and threading to start httpd # skip for now print 'reloader bypassed for Windows service' pass # klass.inner_run(*args, **options) import errno import socket from django.utils import six from django.utils.six.moves import socketserver from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler from datetime import datetime from django.conf import settings from django.utils import translation threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' klass.stdout.write("Validating models...\n\n") klass.validate(display_num_errors=True) klass.stdout.write(( "%(started_at)s\n" "Django version %(version)s, using settings %(settings)r\n" "Starting development server at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "started_at": datetime.now().strftime('%B %d, %Y - %X'), "version": klass.get_version(), "settings": settings.SETTINGS_MODULE, "addr": '[%s]' % klass.addr if klass._raw_ipv6 else klass.addr, "port": klass.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = klass.get_handler(*args, **options) # run(addr=klass.addr, port=int(klass.port), wsgi_handler=handler, # ipv6=klass.use_ipv6, threading=threading) server_address = (klass.addr, int(klass.port)) if threading: httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {}) else: httpd_cls = WSGIServer httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=klass.use_ipv6) httpd.set_app(handler) except socket.error as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { errno.EACCES: "You don't have permission to access that port.", errno.EADDRINUSE: "That port is already in use.", errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.", } try: error_text = ERRORS[e.errno] except KeyError: error_text = str(e) klass.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) finally: if saved_locale is not None: translation.activate(saved_locale) return httpd
def test_uses_base_template(self): activate('en') response = self.client.get(reverse("home")) self.assertTemplateUsed(response, "base.html")
def _render_template(self, template, context): translation.activate(self._language or settings.LANGUAGE_CODE) return Template(template).render(Context(context))
def setlang(request, lang): user_language = lang translation.activate(user_language) response = redirect(request.META.get('HTTP_REFERER')) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) return response
def __enter__(self): self._old_language = translation.get_language() translation.activate(lang)
def execute(self, data, parent_data): executor = parent_data.get_one_of_inputs('executor') biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id') client = get_client_by_user(executor) client.set_bk_api_ver('v2') if parent_data.get_one_of_inputs('language'): setattr(client, 'language', parent_data.get_one_of_inputs('language')) translation.activate(parent_data.get_one_of_inputs('language')) # 查询主机id ip_list = get_ip_by_regex(data.get_one_of_inputs('cc_host_ip')) host_result = cc_get_host_id_by_innerip(executor, biz_cc_id, ip_list) if not host_result['result']: data.set_outputs('ex_data', host_result['message']) return False # 更新主机属性 cc_host_property = data.get_one_of_inputs('cc_host_property') if cc_host_property == "bk_isp_name": bk_isp_name = cc_format_prop_data( executor, 'host', 'bk_isp_name', parent_data.get_one_of_inputs('language')) if not bk_isp_name['result']: data.set_outputs('ex_data', bk_isp_name['message']) return False cc_host_prop_value = bk_isp_name['data'].get( data.get_one_of_inputs('cc_host_prop_value')) if not cc_host_prop_value: data.set_outputs('ex_data', _(u"所属运营商校验失败,请重试并修改为正确的所属运营商")) return False elif cc_host_property == "bk_state_name": bk_state_name = cc_format_prop_data( executor, 'host', 'bk_state_name', parent_data.get_one_of_inputs('language')) if not bk_state_name['result']: data.set_outputs('ex_data', bk_state_name['message']) return False cc_host_prop_value = bk_state_name['data'].get( data.get_one_of_inputs('cc_host_prop_value')) if not cc_host_prop_value: data.set_outputs('ex_data', _(u"所在国家校验失败,请重试并修改为正确的所在国家")) return False elif cc_host_property == "bk_province_name": bk_province_name = cc_format_prop_data( executor, 'host', 'bk_province_name', parent_data.get_one_of_inputs('language')) if not bk_province_name['result']: data.set_outputs('ex_data', bk_province_name['message']) return False cc_host_prop_value = bk_province_name['data'].get( data.get_one_of_inputs('cc_host_prop_value')) if not cc_host_prop_value: data.set_outputs('ex_data', _(u"所在省份校验失败,请重试并修改为正确的所在省份")) return False else: cc_host_prop_value = data.get_one_of_inputs('cc_host_prop_value') cc_kwargs = { "bk_host_id": ",".join(host_result['data']), "data": { cc_host_property: cc_host_prop_value } } cc_result = client.cc.update_host(cc_kwargs) if cc_result['result']: return True else: message = cc_handle_api_error('cc.update_host', cc_kwargs, cc_result['message']) data.set_outputs('ex_data', message) return False
def handle(self, *args, **options): style = no_style() if options['no_color'] else color_style() language = options['language'] if language is not None: translation.activate(language) self.LANGUAGES = [ (code, name) for code, name in getattr(settings, 'LANGUAGES', []) if code == language ] else: self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), )) decorator = options['decorator'] if not decorator: decorator = ['login_required'] format_style = options['format_style'] if format_style not in FMTR: raise CommandError( "Format style '%s' does not exist. Options: %s" % ( format_style, ", ".join(sorted(FMTR.keys())), )) pretty_json = format_style == 'pretty-json' if pretty_json: format_style = 'json' fmtr = FMTR[format_style] urlconf = options['urlconf'] views = [] if not hasattr(settings, urlconf): raise CommandError( "Settings module {} does not have the attribute {}.".format( settings, urlconf)) try: urlconf = __import__(getattr(settings, urlconf), {}, {}, ['']) except Exception as e: if options['traceback']: import traceback traceback.print_exc() raise CommandError("Error occurred while trying to load %s: %s" % (getattr(settings, urlconf), str(e))) view_functions = self.extract_views_from_urlpatterns( urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__globals__'): func_globals = func.__globals__ elif hasattr(func, 'func_globals'): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] if isinstance(func, functools.partial): func = func.func decorators.insert(0, 'functools.partial') if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) module = '{0}.{1}'.format(func.__module__, func_name) url_name = url_name or '' url = simplify_regex(regex) decorator = ', '.join(decorators) if format_style == 'json': views.append({ "url": url, "module": module, "name": url_name, "decorators": decorator }) else: views.append( fmtr.format( module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)), url_name=style.URL_NAME(url_name), url=style.URL(url), decorator=decorator, ).strip()) if not options['unsorted'] and format_style != 'json': views = sorted(views) if format_style == 'aligned': views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ ' '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) for row in views ] elif format_style == 'table': # Reformat all data and show in a table format views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator')) table_views.append(' | '.join( '{0:<{1}}'.format(title, width) for width, title in zip(widths, header))) table_views.append('-+-'.join('-' * width for width in widths)) for row in views: table_views.append(' | '.join( '{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row))) # Replace original views so we can return the same object views = table_views elif format_style == 'json': if pretty_json: return json.dumps(views, indent=4) return json.dumps(views) return "\n".join([v for v in views]) + "\n"
def __exit__(self, *args): translation.activate(self._old_language)
def handle(self, *args, **options): activate("ru") tenhou_nicknames = {} players = TournamentPlayers.objects.filter( tournament_id=settings.TOURNAMENT_ID) for tournament_player in players: try: tenhou_obj = TenhouNickname.objects.get( tenhou_username=tournament_player.tenhou_username) stat_obj = tenhou_obj.aggregated_statistics.filter( game_players=TenhouAggregatedStatistics.FOUR_PLAYERS ).first() tenhou_nicknames[ tournament_player.tenhou_username] = stat_obj.rank except TenhouNickname.DoesNotExist: print( f"Downloading tenhou stat for {tournament_player.tenhou_username}..." ) player_games, account_start_date, four_players_rate = download_all_games_from_nodochi( tournament_player.tenhou_username) is_main = False player = Player.objects.all().first() tenhou_object = TenhouNickname.objects.create( is_main=is_main, player=player, tenhou_username=tournament_player.tenhou_username, username_created_at=account_start_date, ) save_played_games(tenhou_object, player_games) stat_obj = recalculate_tenhou_statistics_for_four_players( tenhou_object, player_games, four_players_rate) tenhou_nicknames[ tournament_player.tenhou_username] = stat_obj.rank sleep(2) for nickname in tenhou_nicknames.keys(): stat_rank = tenhou_nicknames[nickname] if stat_rank >= 10: dan = stat_rank - 9 else: if stat_rank == 0: stat_rank = 1 dan = stat_rank / 10 tenhou_nicknames[nickname] = dan with open(TeamSeating.processed_seating) as f: data = json.loads(f.read()) for round_index in range(7): print(f"Раунд/Hanchan {round_index + 1}") print("") seating = data["seating"][round_index] for table_index, table in enumerate(seating): print(f"Стол/Table {table_index + 1}") player_names = [] # replace team numbers with pantheon ids dans = 0 for x in range(0, 4): pantheon_id = data["team_players_map"][str(table[x])] tournament_player = TournamentPlayers.objects.get( tournament_id=settings.TOURNAMENT_ID, pantheon_id=pantheon_id) last_name, first_name = self.get_player_name( tournament_player) player_names.append(f"{last_name} {first_name}") dans += tenhou_nicknames[tournament_player.tenhou_username] print(f"{','.join(player_names)},{(dans/4):.2f}") print("")
def user_profile(request): profile = request.user.profile form_classes = [ ProfileForm, SubscriptionForm, SubscriptionSettingsForm, UserSettingsForm, ] if request.method == 'POST': # Parse POST params forms = [form(request.POST, instance=profile) for form in form_classes] forms.append(UserForm(request.POST, instance=request.user)) if appsettings.DEMO_SERVER and request.user.username == 'demo': return deny_demo(request) if all([form.is_valid() for form in forms]): # Save changes for form in forms: form.save() # Change language set_lang(request, request.user.profile) # Redirect after saving (and possibly changing language) response = redirect('profile') # Set language cookie and activate new language (for message below) lang_code = profile.language response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) translation.activate(lang_code) messages.success(request, _('Your profile has been updated.')) return response else: forms = [form(instance=profile) for form in form_classes] forms.append(UserForm(instance=request.user)) social = request.user.social_auth.all() social_names = [assoc.provider for assoc in social] all_backends = set(load_backends(BACKENDS).keys()) new_backends = [ x for x in all_backends if x == 'email' or x not in social_names ] license_projects = SubProject.objects.filter( project__in=Project.objects.all_acl(request.user) ).exclude( license='' ) response = render( request, 'accounts/profile.html', { 'form': forms[0], 'subscriptionform': forms[1], 'subscriptionsettingsform': forms[2], 'usersettingsform': forms[3], 'userform': forms[4], 'profile': profile, 'title': _('User profile'), 'licenses': license_projects, 'associated': social, 'new_backends': new_backends, } ) response.set_cookie( settings.LANGUAGE_COOKIE_NAME, profile.language ) return response
def process_request(self, request): language = get_language_from_path(request.path_info) if language: translation.activate(language) request.LANGUAGE_CODE = translation.get_language()
def delete_deactivated_users_task(): from .utils import delete_deactivated_users translation.activate(settings.LANGUAGE_CODE) delete_deactivated_users()
def do_action(self): # check before start access_token = dingtalk_get_access_token() if not access_token: self.log_error('can not get access_token') self.dingtalk_message_send_to_conversation_url = DINGTALK_MESSAGE_SEND_TO_CONVERSATION_URL + '?access_token=' + access_token self.detail_url = get_site_scheme_and_netloc().rstrip('/') + reverse('user_notification_list') site_name = get_site_name() # start now = datetime.now() today = datetime.now().replace(hour=0).replace(minute=0).replace( second=0).replace(microsecond=0) # 1. get all users who are connected dingtalk socials = SocialAuthUser.objects.filter(provider='dingtalk') users = [(x.username, x.uid) for x in socials] self.log_info('Found %d users' % len(users)) if not users: return user_uid_map = {} for username, uid in users: user_uid_map[username] = dingtalk_get_userid_by_unionid(uid) # 2. get previous time that command last runs try: cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 3. get all unseen notices for those users qs = UserNotification.objects.filter( timestamp__gt=last_check_dt ).filter(seen=False).filter( to_user__in=list(user_uid_map.keys()) ) self.log_info('Found %d notices' % qs.count()) if qs.count() == 0: return user_notices = {} for q in qs: if q.to_user not in user_notices: user_notices[q.to_user] = [q] else: user_notices[q.to_user].append(q) # save current language cur_language = translation.get_language() # active zh-cn translation.activate('zh-cn') self.log_info('the language is set to zh-cn') # 4. send msg to users for username, uid in users: user_id = user_uid_map[username] notices = user_notices.get(username, []) count = len(notices) if count == 0: continue title = ungettext( "\n" "You've got 1 new notice on %(site_name)s:\n", "\n" "You've got %(num)s new notices on %(site_name)s:\n", count ) % {'num': count, 'site_name': site_name, } content = ' \n '.join([remove_html_a_element(x.format_msg()) for x in notices]) self.send_dingtalk_msg(user_id, title, content) # reset language translation.activate(cur_language) self.log_info('reset language success')
def get_form_kwargs(self): self.invite = get_object_or_404(Invite, pk=self.kwargs['pk']) translation.activate(self.invite.language) kwargs = super().get_form_kwargs() kwargs['invite'] = self.invite return kwargs
def ready(self): # Imports are inside the function because its point is to avoid importing # the models when django.contrib."MODELS" isn't installed. from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site # If PostgreSQL service is not started the const may not be set # Django doesn't complain # This happens when the server starts at power up # first launching uwsgi before PostgreSQL db_started = False while not db_started: try: db_started = connection.cursor() is not None except: print("waiting for database connection") time.sleep(1) from repanier.models.configuration import Configuration from repanier.models.lut import LUT_DepartmentForCustomer from repanier.models.product import Product from repanier.const import DECIMAL_ONE, PERMANENCE_NAME_PERMANENCE, CURRENCY_EUR, ORDER_GROUP, \ INVOICE_GROUP, CONTRIBUTOR_GROUP, COORDINATION_GROUP, WEBMASTER_GROUP try: # Create if needed and load RepanierSettings var when performing config.save() translation.activate(settings.LANGUAGE_CODE) config = Configuration.objects.filter(id=DECIMAL_ONE).first() if config is None: group_name = settings.ALLOWED_HOSTS[0] site = Site.objects.get_current() if site is not None: site.name = group_name site.domain = group_name site.save() config = Configuration.objects.create( group_name=group_name, name=PERMANENCE_NAME_PERMANENCE, bank_account="BE99 9999 9999 9999", currency=CURRENCY_EUR) config.save() # Purchase.objects.filter(customer_charged__isnull=True).update( # customer_charged=F('customer_invoice__customer_charged') # ) # for purchase in Purchase.objects.filter( # customer_charged__isnull=True).select_related("customer_invoice").order_by('?'): # purchase.customer_charged = purchase.customer_invoice.customer_charged # purchase.save(update_fields=["customer_charged",]) # Staff.objects.rebuild() Product.objects.filter(is_box=True).order_by('?').update( limit_order_quantity_to_stock=True) # Create groups with correct rights order_group = Group.objects.filter( name=ORDER_GROUP).only('id').order_by('?').first() if order_group is None: order_group = Group.objects.create(name=ORDER_GROUP) invoice_group = Group.objects.filter( name=INVOICE_GROUP).only('id').order_by('?').first() if invoice_group is None: invoice_group = Group.objects.create(name=INVOICE_GROUP) contributor_group = Group.objects.filter( name=CONTRIBUTOR_GROUP).only('id').order_by('?').first() if contributor_group is None: contributor_group = Group.objects.create( name=CONTRIBUTOR_GROUP) coordination_group = Group.objects.filter( name=COORDINATION_GROUP).only('id').order_by('?').first() if coordination_group is None: coordination_group = Group.objects.create( name=COORDINATION_GROUP) content_types = ContentType.objects.exclude(app_label__in=[ 'admin', # 'aldryn_bootstrap3', 'auth', 'cascade_dummy', 'cms', 'cmsplugin_cascade', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_image', 'cmsplugin_filer_link', 'cmsplugin_filer_video', 'contenttypes', 'djangocms_text_ckeditor', 'easy_thumbnails', 'filer' 'menus', 'reversion', 'sessions', 'sites', ]).only('id').order_by('?') permissions = Permission.objects.filter( content_type__in=content_types).only('id').order_by('?') order_group.permissions.set(permissions) invoice_group.permissions.set(permissions) coordination_group.permissions.set(permissions) contributor_group.permissions.set(permissions) # WEBMASTER webmaster_group = Group.objects.filter( name=WEBMASTER_GROUP).only('id').order_by('?').first() if webmaster_group is None: webmaster_group = Group.objects.create(name=WEBMASTER_GROUP) content_types = ContentType.objects.exclude(app_label__in=[ 'repanier', 'admin', 'auth', 'contenttypes', 'menus', 'repanier', 'reversion', 'sessions', 'sites', ]).only('id').order_by('?') permissions = Permission.objects.filter( content_type__in=content_types).only('id').order_by('?') webmaster_group.permissions.set(permissions) if LUT_DepartmentForCustomer.objects.count() == 0: # Generate a template of LUT_DepartmentForCustomer parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Vegetables")) LUT_DepartmentForCustomer.objects.create( short_name=_("Basket of vegetables"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Salads"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Tomatoes"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Potatoes"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Greens"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Cabbage"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Fruits")) LUT_DepartmentForCustomer.objects.create( short_name=_("Basket of fruits"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Apples"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Pears"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Plums"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Bakery")) LUT_DepartmentForCustomer.objects.create(short_name=_("Flour"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Bread"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Pastry"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Butchery")) LUT_DepartmentForCustomer.objects.create( short_name=_("Delicatessen"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Chicken"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Pork"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Beef"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Beef and pork"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Veal"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Lamb"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Grocery")) LUT_DepartmentForCustomer.objects.create( short_name=_("Takeaway"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Pasta"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Chocolates"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Oils"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Eggs"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Jams"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Cookies"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Creamery")) LUT_DepartmentForCustomer.objects.create(short_name=_("Dairy"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Cow cheese"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Goat cheese"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Sheep cheese"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Mixed cheese"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Icecream")) LUT_DepartmentForCustomer.objects.create( short_name=_("Cup of icecream"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Icecream per liter"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Icecream in frisco"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Icecream cake"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Sorbet")) LUT_DepartmentForCustomer.objects.create( short_name=_("Cup of sorbet"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Sorbet per liter"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Drink")) LUT_DepartmentForCustomer.objects.create( short_name=_("Juices"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Coffees"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Teas"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Herbal teas"), parent=parent) LUT_DepartmentForCustomer.objects.create(short_name=_("Wines"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Aperitifs"), parent=parent) LUT_DepartmentForCustomer.objects.create( short_name=_("Liqueurs"), parent=parent) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Hygiene")) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Deposit")) parent = LUT_DepartmentForCustomer.objects.create( short_name=_("Subscription")) except Exception as error_str: print("##################################") print(error_str) print("##################################") other = _("Other qty")
def setUp(self): translation.activate('en') super(TestURNStageDuplicateCases, self).setUp() self.case.pk = None self.case.save()