i have pages with multiple languages... something like this:
/ - > en,us,pt,es and the default is US
/foo - > pt,en and default is PT
/bar -> pt and default is PT
on the database i have:
|--URL--|-Languages-|-defLang-
| foo | pt,us | pt
| bar | pt | pt
on the __init__.py i've set it like this:
tsf = TranslationStringFactory('myproject')
def add_renderer_globals(event):
request = event['request']
event['_'] = request.translate
event['localizer'] = request.localizer
def add_localizer(event):
request = event.request
languages = ('en','us','es')
deflang = 'pt'
# CHECK current page
if 'page' in request.matchdict:
currentpage = DBSession.query(Pages).filter_by(url=request.matchdict['page']).first()
#SET pages languages
languages = currentpage.Languages.split(',')
deflang = currentpage.defLang
if not default_locale_negotiator(request):
#set language
request._LOCALE_ = request.accept_language.best_match(languages , deflang)
localizer = get_localizer(request)
request.lang = localizer.locale_name
def auto_translate(string):
return localizer.translate(self.tsf(string))
request.localizer = localizer
request.translate = auto_translate
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
session_factory = session_factory_from_settings(settings)
config = Configurator(settings=settings)
config.include('pyramid_mailer')
config.set_session_factory(session_factory)
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_subscriber(add_renderer_globals, BeforeRender)
config.add_subscriber(add_localizer, ContextFound)
config.add_translation_dirs('myproject:locale/')
config.add_route('home', '/')
config.add_route('page', '/{page}')
config.scan()
return config.make_wsgi_app()
but that's not working, only the home it's working fine
if i'm missing any info please warn me.
thanks
It looks to me like you are searching for 'entity' in request.matchdict when in reality you should be searching for 'page', given your route '/{page}'.
def add_localizer(event):
request = event.request
languages = ('en','us','es')
deflang = 'pt'
# CHECK current page
if 'page' in request.matchdict:
currentpage = DBSession.query(Pages).filter_by(url=request.matchdict['page']).first()
#SET pages languages
languages = currentpage.Languages.split(',')
deflang = currentpage.defLang
#----- CHANGED ----------------------
dln = default_locale_negotiator(request)
if not dln or dln not in languages:
#set the default language
request._LOCALE_ = deflang
localizer = get_localizer(request)
request.lang = localizer.locale_name
def auto_translate(string):
return localizer.translate(self.tsf(string))
request.localizer = localizer
request.translate = auto_translate
thanks
Related
I am a newcomer and try to use doxygen for generate documentation. I use annotation for public attributes of classes to avoid type problems. But for a simple code:
class doxygenchk:
def __init__(self):
self.attr: float = 1.
self.visible_attr = 2.
The result in the documentation is:
Public Member Functions
def __init__ (self)
Public Attributes
visible_attr
The annotated attr atribute does not appear.
Is there a way to force doxygen to recognize annotated attribute?
I use doxygen version 1.8.17
doxygen was optimized for java, the output in doxywizard is:
Searching for include files...
Searching for example files...
Searching for images...
Searching for dot files...
Searching for msc files...
Searching for dia files...
Searching for files to exclude
Searching INPUT for files to process...
Searching for files in directory .../tmpproject
Reading and parsing tag files
Parsing files
Reading .../tmpproject/main.py...
Parsing file .../tmpproject/main.py...
Reading .../tmpproject/tmpguide.py...
Parsing file .../tmpproject/tmpguide.py...
Building group list...
Building directory list...
Building namespace list...
Building file list...
Building class list...
Computing nesting relations for classes...
Associating documentation with classes...
Building example list...
Searching for enumerations...
Searching for documented typedefs...
Searching for members imported via using declarations...
Searching for included using directives...
Searching for documented variables...
Building interface member list...
Building member list...
Searching for friends...
Searching for documented defines...
Computing class inheritance relations...
Computing class usage relations...
Flushing cached template relations that have become invalid...
Computing class relations...
Add enum values to enums...
Searching for member function documentation...
Creating members for template instances...
Building page list...
Search for main page...
Computing page relations...
Determining the scope of groups...
Sorting lists...
Determining which enums are documented
Computing member relations...
Building full member lists recursively...
Adding members to member groups.
Computing member references...
Inheriting documentation...
Generating disk names...
Adding source references...
Adding xrefitems...
Sorting member lists...
Setting anonymous enum type...
Computing dependencies between directories...
Generating citations page...
Counting members...
Counting data structures...
Resolving user defined references...
Finding anchors and sections in the documentation...
Transferring function references...
Combining using relations...
Adding members to index pages...
Correcting members for VHDL...
Generating style sheet...
Generating search indices...
Generating example documentation...
Generating file sources...
Generating file documentation...
Generating docs for file main.py...
Generating docs for file tmpguide.py...
Generating page documentation...
Generating group documentation...
Generating class documentation...
Generating namespace index...
Generating docs for namespace main
Generating docs for namespace tmpguide
Generating docs for compound tmpguide::doxygenchk...
Generating graph info page...
Generating directory documentation...
Generating index page...
Generating page index...
Generating module index...
Generating namespace index...
Generating namespace member index...
Generating annotated compound index...
Generating alphabetical compound index...
Generating hierarchical class index...
Generating member index...
Generating file index...
Generating file member index...
Generating example index...
finalizing index lists...
writing tag file...
Running plantuml with JAVA...
lookup cache used 4/65536 hits=5 misses=4
finished...
*** Doxygen has finished
The configuration is:
# Doxyfile 1.8.17
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "My Project"
PROJECT_NUMBER =
PROJECT_BRIEF =
PROJECT_LOGO =
OUTPUT_DIRECTORY = ../tmpproject/docs
CREATE_SUBDIRS = NO
ALLOW_UNICODE_NAMES = NO
OUTPUT_LANGUAGE = English
OUTPUT_TEXT_DIRECTION = None
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
contains \
represents \
a \
an \
the
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = NO
FULL_PATH_NAMES = YES
STRIP_FROM_PATH =
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = NO
JAVADOC_BANNER = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = NO
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 4
ALIASES =
TCL_SUBST =
OPTIMIZE_OUTPUT_FOR_C = NO
OPTIMIZE_OUTPUT_JAVA = YES
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
OPTIMIZE_OUTPUT_SLICE = NO
EXTENSION_MAPPING =
MARKDOWN_SUPPORT = YES
TOC_INCLUDE_HEADINGS = 5
AUTOLINK_SUPPORT = YES
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
GROUP_NESTED_COMPOUNDS = NO
SUBGROUPING = YES
INLINE_GROUPED_CLASSES = NO
INLINE_SIMPLE_STRUCTS = NO
TYPEDEF_HIDES_STRUCT = NO
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = YES
EXTRACT_PRIVATE = NO
EXTRACT_PRIV_VIRTUAL = NO
EXTRACT_PACKAGE = NO
EXTRACT_STATIC = NO
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = NO
EXTRACT_ANON_NSPACES = NO
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
HIDE_IN_BODY_DOCS = NO
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = NO
HIDE_SCOPE_NAMES = NO
HIDE_COMPOUND_REFERENCE= NO
SHOW_INCLUDE_FILES = YES
SHOW_GROUPED_MEMB_INC = NO
FORCE_LOCAL_INCLUDES = YES
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = NO
SORT_BY_SCOPE_NAME = NO
STRICT_PROTO_MATCHING = NO
GENERATE_TODOLIST = YES
GENERATE_TESTLIST = YES
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_AS_ERROR = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = ../tmpproject
INPUT_ENCODING = UTF-8
FILE_PATTERNS = *.c \
*.cc \
*.cxx \
*.cpp \
*.c++ \
*.java \
*.ii \
*.ixx \
*.ipp \
*.i++ \
*.inl \
*.idl \
*.ddl \
*.odl \
*.h \
*.hh \
*.hxx \
*.hpp \
*.h++ \
*.cs \
*.d \
*.php \
*.php4 \
*.php5 \
*.phtml \
*.inc \
*.m \
*.markdown \
*.md \
*.mm \
*.dox \
*.doc \
*.txt \
*.py \
*.pyw \
*.f90 \
*.f95 \
*.f03 \
*.f08 \
*.f \
*.for \
*.tcl \
*.vhd \
*.vhdl \
*.ucf \
*.qsf \
*.ice
RECURSIVE = NO
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS =
EXCLUDE_SYMBOLS =
EXAMPLE_PATH =
EXAMPLE_PATTERNS = *
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
FILTER_SOURCE_PATTERNS =
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = NO
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
SOURCE_TOOLTIPS = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
CLANG_ASSISTED_PARSING = NO
CLANG_OPTIONS =
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = YES
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
HTML_TIMESTAMP = NO
HTML_DYNAMIC_MENUS = YES
HTML_DYNAMIC_SECTIONS = NO
HTML_INDEX_NUM_ENTRIES = 100
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_BUNDLE_ID = org.doxygen.Project
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
DOCSET_PUBLISHER_NAME = Publisher
GENERATE_HTMLHELP = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
GENERATE_TREEVIEW = NO
ENUM_VALUES_PER_LINE = 4
TREEVIEW_WIDTH = 250
EXT_LINKS_IN_WINDOW = NO
FORMULA_FONTSIZE = 10
FORMULA_TRANSPARENT = YES
FORMULA_MACROFILE =
USE_MATHJAX = NO
MATHJAX_FORMAT = HTML-CSS
MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/
MATHJAX_EXTENSIONS =
MATHJAX_CODEFILE =
SEARCHENGINE = YES
SERVER_BASED_SEARCH = NO
EXTERNAL_SEARCH = NO
SEARCHENGINE_URL =
SEARCHDATA_FILE = searchdata.xml
EXTERNAL_SEARCH_ID =
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = YES
LATEX_OUTPUT = latex
LATEX_CMD_NAME =
MAKEINDEX_CMD_NAME = makeindex
LATEX_MAKEINDEX_CMD = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4
EXTRA_PACKAGES =
LATEX_HEADER =
LATEX_FOOTER =
LATEX_EXTRA_STYLESHEET =
LATEX_EXTRA_FILES =
PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_SOURCE_CODE = NO
LATEX_BIB_STYLE = plain
LATEX_TIMESTAMP = NO
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
RTF_SOURCE_CODE = NO
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = YES
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_SUBDIR =
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_PROGRAMLISTING = YES
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
GENERATE_DOCBOOK = NO
DOCBOOK_OUTPUT = docbook
DOCBOOK_PROGRAMLISTING = NO
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = NO
EXPAND_ONLY_PREDEF = NO
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = NO
DIA_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = NO
DOT_NUM_THREADS = 0
DOT_FONTNAME = Helvetica
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
UML_LIMIT_NUM_FIELDS = 10
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = NO
CALLER_GRAPH = NO
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
INTERACTIVE_SVG = NO
DOT_PATH =
DOTFILE_DIRS =
MSCFILE_DIRS =
DIAFILE_DIRS =
PLANTUML_JAR_PATH =
PLANTUML_CFG_FILE =
PLANTUML_INCLUDE_PATH =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = NO
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
Finally I have found a relatively simple solution:
if each object variable is defined as class variable, but it is redefined in __init__() then you get a dirty workaround till you do not find the proper documentation writer that fulfills all of your needs
I have went through other answers but none of them seems to answer this question , I have cloned sandman2 which does not have column filter and column searchable option in admin dashboard , below is the ModelView
from flask_admin.contrib.sqla import ModelView
class CustomAdminView(ModelView): # pylint: disable=no-init
"""Define custom templates for each view."""
list_template = 'list.html'
create_template = 'create.html'
edit_template = 'edit.html'
column_display_pk = True
ModelView.can_export = True
ModelView.can_delete = False
ModelView.can_view_details = True
ModelView.can_set_page_size = True
ModelView.can_create = False
ModelView.page_size = 500
And I am calling this in app.py
def register_model(cls, admin=None):
"""Register *cls* to be included in the API service
:param cls: Class deriving from :class:`sandman2.models.Model`
"""
cls.__url__ = '/{}'.format(cls.__name__.lower())
service_class = type(
cls.__name__ + 'Service',
(Service,),
{
'__model__': cls,
})
# inspect primary key
cols = list(cls().__table__.primary_key.columns)
# composite keys not supported (yet)
primary_key_type = 'string'
if len(cols) == 1:
col_type = cols[0].type
# types defined at http://flask.pocoo.org/docs/0.10/api/#url-route-registrations
if isinstance(col_type, sqltypes.String):
primary_key_type = 'string'
elif isinstance(col_type, sqltypes.Integer):
primary_key_type = 'int'
elif isinstance(col_type, sqltypes.Numeric):
primary_key_type = 'float'
# registration
register_service(service_class, primary_key_type)
if admin is not None:
columns = (c.name for c in (list(cls().__table__.columns)) if not c.primary_key)
cv = CustomAdminView(cls, db.session)
cv.column_filters = columns
cv.column_searchable_list = list(columns)
admin.add_view(cv)
Still no luck , no filter option on the admin neither the filter option.
I'm currently building a Tool that generates a PDF report using Python pdfkit and jinja.
This report builds on a lot of static html and around 30 functions that produces data and images (charts) for the report. These functions all access external data through pyodbc or pandas from_sql.
I am now running into performance issues, and the report takes around 5 minutes to build.
I'm hoping to utilize multithreading in order to build a dictionary of data, but have not been able to figure out how to approach the issue.
My current code looks something like this.
def buildReport():
if checkKvaegCVR(SQL = checkKvaegCVRSQL(cvrNummer = cvrNummer), cursor = OEDBCursor):
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("templates/kvaeg/kvaegBase.html")
pdfOptions = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'quiet': '',
'encoding': "UTF-8",
'footer-right': '[page]'
}
css = 'static/css/style.css'
template_vars = {'kvaegForsideBillede': imageBuilder()['kvaegForsideBillede'],
'bagsideBillede': imageBuilder()['bagsideBillede'],
'navn' : bedriftAdresse(cvrNummer = cvrNummer,
cursor = KundeAnalyseDBCursor)[0],
'adresse' : bedriftAdresse(cvrNummer = cvrNummer,
cursor = KundeAnalyseDBCursor)[1],
'postnrBy' : str(int(bedriftAdresse(cvrNummer = cvrNummer, cursor = KundeAnalyseDBCursor)[2])) + ' ' +
bedriftAdresse(cvrNummer = cvrNummer, cursor = KundeAnalyseDBCursor)[3],
'fremstillingsprisKorr': imageBuilder()['fremstillingsprisKorr'],
'fremstillingsprisForbedring':imageBuilder()['fremstillingsprisForbedring'],
'graesoptagelse':kgGraesPrKo(),
'indreSaedskifteKort':indreSaedskifteKortPNG(CVRPunkt = CVRPunkt(cvrNummer, KundeAnalyseDBCursor),
CVRBuffer = CVRBuffer(cvrNummer, KundeAnalyseDBCursor),
indreSaedskifteKort = indreSaedskifteKort(indreSaedskifteKortSQL = indreSaedskifteKortSQL(cvrNummer = cvrNummer), cursor = KundeAnalyseDBCursor)),
'naboKort':naboKortPNG(CVRPunkt = CVRPunkt(cvrNummer = cvrNummer, cursor = KundeAnalyseDBCursor),
CVRBuffer = CVRBuffer(cvrNummer = cvrNummer, cursor = KundeAnalyseDBCursor),
naboKort = naboKort(naboMarkerSQL = naboMarkerSQL(cvrNummer = cvrNummer),
egneMarkerSQL = egneMarkerSQL(cvrNummer = cvrNummer),
cursor = KundeAnalyseDBCursor))
...
...
30 more functions here
...
...}
pdfkit.from_string(template.render(template_vars), 'KvaegRapport - {}.pdf'.format(cvrNummer), options=pdfOptions, css=css)
print('Rapporten er klar')
else:
print('Kan ikke bygge rapport på dette CVR nummer')
I would like to build the dictionary "Template_vars" using multithreading (probably outside my main function)
Any suggestions?
I could suggest following but with multiprocessing (the following code has not been tested):
from multiprocessing import Process, Queue
def make_smth(func, queue, name, *args, **kwargs):
queue.put((name, func(*args, **kwargs)))
result_queue = Queue()
processes = list()
processes.append(
Process(target=make_smth,
args=(bedriftAdresse, result_queue, "navn"),
kwargs={cvrNummer: cvrNummer, cursor: KundeAnalyseDBCursor[0]}
)
)
processes.append(
Process(target=make_smth,
args=(kgGraesPrKo, result_queue, "graesoptagelse"),
kwargs={}
)
)
#...... You should do it for each of your functions
for p in processes:
p.start()
template_vars = {}
result = result_queue.get()
while result:
template_vars[result[0]] = result[1]
result = result_queue.get()
Reading the documentation about applying the MVC pattern with TraitsUI, I read the example MVC_demo.py. Now, I'm wondering how to manage multiple "MVC".
I want to write some "includeallMVCs.py" and to have something like:
import MyViewController1, MyViewController2, MyViewController2
class IncludeallMVCs(HasTraits):
view = Include(MyViewController1, MyViewController2, MyViewController3)
Where MyViewController, MyViewController, MyViewController are classes like the MVC_demo sample.
So, the idea is to separate differents views with their controllers, and then "join" all of them in only one "generic" view.
Searching in the examples I found this one: Dynamic Forms Using Instances
Then I modified it to separate an AdultHandler. In this example I use the salary variable to be controlled by AdultHandler.
File: adult.py
from traitsui.api import Handler
class AdultHandler(Handler):
def object_salary_changed (self, info):
if (info.object.salary >= 20000):
print "Good Salary!"
else:
print "Bad Salary"
File: adult_model.py
from adult import AdultHandler
class AdultSpec ( HasTraits ):
""" Trait list for adults (assigned to 'misc' for a Person when age >= 18).
"""
marital_status = Enum( 'single', 'married', 'divorced', 'widowed' )
registered_voter = Bool
military_service = Bool
salary = Int
traits_view = View(
'marital_status',
'registered_voter',
'military_service',
'salary',
handler = AdultHandler()
)
if __name__ == '__main__':
a = AdultSpec()
a.configure_traits()
File: main.py
from adult_model import AdultSpec
class Person ( HasTraits ):
""" Demo class for demonstrating dynamic interface restructuring.
"""
datainput = Instance( AdultSpec )
# Interface for attributes that depend on the value of 'age':
spec_group = Group(
Group(
Item( name = 'datainput', style = 'custom' ),
show_labels = False
),
label = 'Additional Info',
show_border = True
)
# A simple View is enough as long as the right handler is specified:
view = View(
Group(
spec_group
),
title = 'Using MVC',
buttons = [ 'OK' ],
resizable = True,
width = 300
)
# Create the demo:
demo = Person( datainput = AdultSpec() )
# Run the demo (if invoked from the command line):
if __name__ == '__main__':
demo.configure_traits()
I use mongoengine and when I call a class mongoengine give me error
for example when I use : Site.objects()
I get this
TypeError: id must be an instance of (str, unicode, ObjectId), not <type 'dict'>
and it's my class definition :
class Site(db.Document):
siteURL = db.URLField('''required = True''')
name = db.StringField(required = True)
pages = db.ListField(ReferenceField(Page))
siteId = db.IntField(required = True , unique = True )
views = db.IntField(required = True , default = 0)
visitors = db.IntField(required = True , default = 0)
stat_by_hour = LimitedListField(EmbeddedDocumentField(HourStat))
weekday_stat = db.ListField(EmbeddedDocumentField(WeekdayStat))
os = db.ListField(ReferenceField(OS))
countries = db.ListField(ReferenceField(Country))
cities = db.ListField(ReferenceField(City))
browsers = db.ListField(ReferenceField(Browser))
resolutions = db.ListField(ReferenceField(Resolution))
mostVisitedDays = db.SortedListField(EmbeddedDocumentField(MostVisitedDay) , ordering="visitors")