Version 2 (modified by trac, 13 months ago) ( diff )

--

TicketQuery Wiki Macro

The TicketQuery macro lets you display ticket information anywhere that accepts WikiFormatting. The query language used by the [[TicketQuery]] macro is described in the TracQuery page.

Usage

[[TicketQuery]]

Wiki macro listing tickets that match certain criteria.

This macro accepts a comma-separated list of keyed parameters, in the form "key=value".

If the key is the name of a field, the value must use the syntax of a filter specifier as defined in TracQuery#QueryLanguage. Note that this is not the same as the simplified URL syntax used for query: links starting with a ? character. Commas (,) can be included in field values by escaping them with a backslash (\).

Groups of field constraints to be OR-ed together can be separated by a literal or argument.

In addition to filters, several other named parameters can be used to control how the results are presented. All of them are optional.

The format parameter determines how the list of tickets is presented:

  • list -- the default presentation is to list the ticket ID next to the summary, with each ticket on a separate line.
  • compact -- the tickets are presented as a comma-separated list of ticket IDs.
  • count -- only the count of matching tickets is displayed
  • rawcount -- only the count of matching tickets is displayed, not even with a link to the corresponding query (since 1.1.1)
  • table -- a view similar to the custom query view (but without the controls)
  • progress -- a view similar to the milestone progress bars

The max parameter can be used to limit the number of tickets shown (defaults to 0, i.e. no maximum).

The order parameter sets the field used for ordering tickets (defaults to id).

The desc parameter indicates whether the order of the tickets should be reversed (defaults to false).

The group parameter sets the field used for grouping tickets (defaults to not being set).

The groupdesc parameter indicates whether the natural display order of the groups should be reversed (defaults to false).

The verbose parameter can be set to a true value in order to get the description for the listed tickets. For table format only. deprecated in favor of the rows parameter

The rows parameter can be used to specify which field(s) should be viewed as a row, e.g. rows=description|summary

The col parameter can be used to specify which fields should be viewed as columns. For table format only.

For compatibility with Trac 0.10, if there's a last positional parameter given to the macro, it will be used to specify the format. Also, using "&" as a field separator still works (except for order) but is deprecated.

Examples

Example Result Macro
Number of Triage tickets: 659 [[TicketQuery(status=new&milestone=,count)]]
Number of new tickets: 659 [[TicketQuery(status=new,count)]]
Number of reopened tickets: 0 [[TicketQuery(status=reopened,count)]]
Number of assigned tickets: 397 [[TicketQuery(status=assigned,count)]]
Number of invalid tickets: 5199 [[TicketQuery(status=closed,resolution=invalid,count)]]
Number of worksforme tickets: 1073 [[TicketQuery(status=closed,resolution=worksforme,count)]]
Number of duplicate tickets: 4340 [[TicketQuery(status=closed,resolution=duplicate,count)]]
Number of wontfix tickets: 4148 [[TicketQuery(status=closed,resolution=wontfix,count)]]
Number of fixed tickets: 18636 [[TicketQuery(status=closed,resolution=fixed,count)]]
Number of untriaged tickets (milestone unset): 1056 [[TicketQuery(status!=closed,milestone=,count)]]
Total number of tickets: 35431 [[TicketQuery(count)]]
Number of tickets reported or owned by current user: 1488 [[TicketQuery(reporter=$USER,or,owner=$USER,count)]]
Number of tickets created this month: 49 [[TicketQuery(created=thismonth..,count)]]
Number of closed Firefox tickets: 8 [[TicketQuery(status=closed,keywords~=firefox,count)]]
Number of closed Opera tickets: 24 [[TicketQuery(status=closed,keywords~=opera,count)]]
Number of closed tickets affecting Firefox and Opera: 0 [[TicketQuery(status=closed,keywords~=firefox opera,count)]]
Number of closed tickets affecting Firefox or Opera: 32 [[TicketQuery(status=closed,keywords~=firefox|opera,count)]]
Number of tickets that affect Firefox or are closed and affect Opera: 32 [[TicketQuery(status=closed,keywords~=opera,or,keywords~=firefox,count)]]
Number of closed Firefox tickets that don't affect Opera: 0 [[TicketQuery(status=closed,keywords~=firefox -opera,count)]]
Last 3 modified tickets: #36183, #24632, #36207 [[TicketQuery(max=3,order=modified,desc=1,compact)]]

Details of ticket #1:

[[TicketQuery(id=1,col=id|owner|reporter,rows=summary,table)]]

Ticket Owner Reporter
#1 Jacob Adrian Holovaty
Summary Create architecture for anonymous sessions

Format: list

[[TicketQuery(version=0.6|0.7&resolution=duplicate)]]

This is displayed as:

No results

[[TicketQuery(id=123)]]

This is displayed as:

#123
Typo in the model_api/#field-types

Format: compact

[[TicketQuery(version=0.6|0.7&resolution=duplicate, compact)]]

This is displayed as:

No results

Format: count

[[TicketQuery(version=0.6|0.7&resolution=duplicate, count)]]

This is displayed as:

0

Format: progress

[[TicketQuery(milestone=0.12.8&group=type,format=progress)]]

This is displayed as:

Uncategorized

2002 / 2002

Bug

10176 / 10535

New feature

3718 / 4113

Cleanup/optimization

5264 / 5565

Format: table

You can choose the columns displayed in the table format (format=table) using col=<field>. You can specify multiple fields and the order they are displayed in by placing pipes (|) between the columns:

[[TicketQuery(max=3,status=closed,order=id,desc=1,format=table,col=resolution|summary|owner|reporter)]]

This is displayed as:

Full rows

In table format you can specify full rows using rows=<field>:

[[TicketQuery(max=3,status=closed,order=id,desc=1,format=table,col=resolution|summary|owner|reporter,rows=description)]]

This is displayed as:

Results (1 - 3 of 34375)

1 2 3 4 5 6 7 8 9 10 11
Ticket Resolution Summary Owner Reporter
#36212 wontfix How about providing type safe access to form field data? Justin Black
Description

Right now only cleaned data is acessed in a dict in python. This means that type hcecking code does not know the type of that dict unless it is described as a typeddict. How about providing type safe access to form field data?

class FormOptions(forms.Form):
    prompt = forms.CharField(widget=forms.Textarea)
    n = forms.IntegerField(min_value=1, max_value=10, initial=1)

form_options = FormOptions({'prompt': 'a', 'n': 2})

one could access it as: form_options.prompt.cleaned_data or form_options.prompt

This would allow code to access type safe values for a form in python.

#36211 invalid Subclassing the "runserver" handler doesn't serve static files Ivan Voras
Description

Just for convenience of development, not for production, I'm trying to write a "runserver" lookalike command that also starts Celery, and also uses the autoloader to do it. So I've subclassed Django's runserver Command class and redefined the handler(). It took me ages to understand RUN_MAIN and process management, but here's the result:

import atexit
import errno
import logging
import os
import re
import socket
import subprocess
from time import sleep

from django.conf import settings
from django.core.management.base import CommandError
from django.core.servers.basehttp import run
from django.db import connections
from django.utils import autoreload
from django.utils.regex_helper import _lazy_re_compile
from django.core.management.commands.runserver import Command as RunserverCommand

log = logging.getLogger("glassior")

naiveip_re = _lazy_re_compile(
    r"""^(?:
(?P<addr>
    (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) |         # IPv4 address
    (?P<ipv6>\[[a-fA-F0-9:]+\]) |               # IPv6 address
    (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN
):)?(?P<port>\d+)$""",
    re.X,
)

celery_process = None

class Command(RunserverCommand):
    help = "Starts a lightweight web server for development and a Celery worker with autoreload."

    def handle(self, *args, **options):
        print('runservercelery: Starting both Django and a Celery worker with autoreload...', os.environ.get("RUN_MAIN", False))

        if not settings.DEBUG and not settings.ALLOWED_HOSTS:
            raise CommandError("You must set settings.ALLOWED_HOSTS if DEBUG is False.")

        self.use_ipv6 = options["use_ipv6"]
        if self.use_ipv6 and not socket.has_ipv6:
            raise CommandError("Your Python does not support IPv6.")
        self._raw_ipv6 = False
        if not options["addrport"]:
            self.addr = ""
            self.port = self.default_port
        else:
            m = re.match(naiveip_re, options["addrport"])
            if m is None:
                raise CommandError(
                    '"%s" is not a valid port number '
                    "or address:port pair." % options["addrport"]
                )
            self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
            if not self.port.isdigit():
                raise CommandError("%r is not a valid port number." % self.port)
            if self.addr:
                if _ipv6:
                    self.addr = self.addr[1:-1]
                    self.use_ipv6 = True
                    self._raw_ipv6 = True
                elif self.use_ipv6 and not _fqdn:
                    raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
        if not self.addr:
            self.addr = self.default_addr_ipv6 if self.use_ipv6 else self.default_addr
            self._raw_ipv6 = self.use_ipv6

        if options["use_reloader"]:
            autoreload.run_with_reloader(self.main_loop, *args, **options)
        else:
            self.main_loop(*args, **options)

    def start_celery(self):
        global celery_process
        if os.environ.get("RUN_MAIN", None) != 'true':
            return

        celery_process = subprocess.Popen(
            'celery -A glassiorapp worker -l info --without-gossip --without-mingle --without-heartbeat -c 1',
            shell=True,
            process_group=0,
        )
        log.info(f"Started celery worker (PID: {celery_process.pid})")


    def our_inner_run(self, *args, **options) -> int | None:
        """
        Taken from django.core.management.commands.runserver.Command.inner_run.
        Returns exit code (None = no error) instead of calling sys.exit().
        """
        # If an exception was silenced in ManagementUtility.execute in order
        # to be raised in the child process, raise it now.
        autoreload.raise_last_exception()

        threading = False # options["use_threading"]
        # 'shutdown_message' is a stealth option.
        shutdown_message = options.get("shutdown_message", "")

        if not options["skip_checks"]:
            self.stdout.write("Performing system checks...\n\n")
            self.check(display_num_errors=True)
        # Need to check migrations here, so can't use the
        # requires_migrations_check attribute.
        self.check_migrations()
        # Close all connections opened during migration checking.
        for conn in connections.all(initialized_only=True):
            conn.close()

        try:
            handler = self.get_handler(*args, **options)
            run(
                self.addr,
                int(self.port),
                handler,
                ipv6=self.use_ipv6,
                threading=threading,
                on_bind=self.on_bind,
                server_cls=self.server_cls,
            )
        except OSError 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 = e
            self.stderr.write("Error: %s" % error_text)
            # Need to use an OS exit because sys.exit doesn't work in a thread
            return 1
        except KeyboardInterrupt:
            print("**** KeyboardInterrupt") # This is never reached.
            if shutdown_message:
                self.stdout.write(shutdown_message)
            return 0

    def main_loop(self, *args, **options):
        self.start_celery()
        exit_code = self.our_inner_run(*args, **options) # Django's code
        # So, apparently our_inner_run doesn't return. 
        print(f"***** our_inner_run exit_code={exit_code}")


@atexit.register
def stop_celery():
    global celery_process
    if celery_process:
        log.info(f"Stopping celery worker (PID: {celery_process.pid})")
        # It's a mess.
        os.system(f"kill -TERM -{celery_process.pid}")
        celery_process = None
        sleep(1)

This works, BUT it doesn't start the static file server. I don't see anything special in the original handler, or in the new one, that would cause this, so I'm just stumped. Switching between running the original runserver and this one, the original serves static files perfectly fine, and this one returns the "no route found" error:

Using the URLconf defined in glassiorapp.urls, Django tried these URL patterns, in this order:

admin/
g/
The current path, static/web/color_modes.js, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

The actual app is being run and responds to the URL endpoints.

Is there something magical about the default runserver?

#36209 duplicate Add HttpResponse subclasses for No Content and Created Michiel Beijen
Description

Django has HttpResponse subclasses for many status codes. Although you can use the generic HttpResponse and provide it with a status code, the subclasses provide for more readable code: it's more clear to write HttpResponseRedirect() or HttpResponsePermanentRedirect() than to use HttpResponse with a 301 or 302 status code, because that requires you to 'know' which status code is which.

However for the RESTful HTTP response codes 201 Created and 204 No Content there are no HttpResponse subclasses. It would be helpful to people writing RESTful HTTP APIs to have HttpResponse subclasses for these codes.

This patch adds HttpResponseCreated and HttpResponseNoContent subclasses. I've targeted Django 6 because 5.2 is closed for new features.

1 2 3 4 5 6 7 8 9 10 11


See also: TracQuery, TracTickets, TracReports

Note: See TracWiki for help on using the wiki.
Back to Top