powered by simpleCommunicator - 2.0.60     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [Python] wsgi приложение
12 сообщений из 12, страница 1 из 1
[Python] wsgi приложение
    #37950159
Viktoria2792
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Здравствуйте! Необходимо написать на Python wsgi приложение заполнения формы обратной связи с сохранением результата в бд. Приложение должно реализовывать возможность просмотра и удаления добавленных записей. Форму я уже создала, база данных создана в mysqlWorkbench.
Не могу понять как писать это приложение и что для этого нужно. Прикрепленный файл содержит реализацию формы с помощью технологии ajax. Очень срочно нужно. Пожалуйста помогите.
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37950691
Фотография FishHook
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Берем любой веб-фреймворк, например Джанго....

.... И пишем
Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
class CallbackFormModel(models.Model):
    user=models.ForeignKey(User)
    field1=models.CarField(max_length=50, verbose_name=u'Поле 1')
    field2=models.IntegerField(verbose_name=u'Поле 2', null=True, blank=True)

class CallbackForm(forms.ModelForm):
    class Meta:
        model=CallbackFormModel

class View(FormView):
    template_name='template'
    form_class=CallbackForm
    success_url='/'    

    def form_valid(self, form):

        form.save()
        return super(View, self).form_valid(form)
    
    def get_form(self, form_class):
        
        instance= CallbackFormModel.get_or_create(user=self.request.user)
        form=form_class(instance=self.child,  **self.get_form_kwargs())
        return form



Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
<html>
<head></head>
<body>

<form method='post'>{% csrf_token %}
{{ form }}
<input type='submit' />
</form>
</body>

</html>
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37951521
Viktoria2792
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А можно без использования django? Просто в задании написано что, для реализации возможно использовать только стандартные библиотеки и модули python версии 2.6. Заранее спасибо!
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37951540
Фотография NekZ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Странные задания дают на собеседованиях)
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37951929
Фотография FishHook
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Viktoria2792А можно без использования django? Просто в задании написано что, для реализации возможно использовать только стандартные библиотеки и модули python версии 2.6. Заранее спасибо!
Студент?
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37953115
Adylov Timur
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Помогите пожалуйста Виктории, бедная девчонка не может разобраться с заданием, а ей очень нужно эта работа. Подтолкните, дайте совет. Время поджимает. Заранее всем огромное спасибо за помощь!!! Если что-то не понятно пишите
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37953154
Фотография NekZ
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Adylov TimurПомогите пожалуйста Виктории, бедная девчонка не может разобраться с заданием, а ей очень нужно эта работа. Подтолкните, дайте совет. Время поджимает. Заранее всем огромное спасибо за помощь!!! Если что-то не понятно пишите
А вы, как я понимаю, тот самый изверг-работодатель?
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37953189
Adylov Timur
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
NekZ,
с чего Вы взяли?
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37953419
Viktoria2792
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Да студентка 4го курса.
...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37953680
Фотография FishHook
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Viktoria2792Да студентка 4го курса.
Что вам нужно:
1. Освоить ЯП Python
2. Прочитать в википедии про wsgi
3. Написать приложение



Веб-сервер
Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

project_dir = os.path.abspath(__file__)
sys.path.insert(0, project_dir)

from app.application import WSGIApplication
app=WSGIApplication(project_dir)

from paste.httpserver import serve
from paste.evalexception import EvalException
from paste.debug.prints import PrintDebugMiddleware
from paste.reloader import install as install_reloader

app = EvalException(app)
app = PrintDebugMiddleware(app)
install_reloader()

serve(app, host='0.0.0.0', port=8080)



Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
class ControllerContext(object):
    """Controller context
    """

    def __init__(self, instance, environ):
        self.instance = instance
        self.request = Request(environ, charset='utf-8')
        self._response = Response(request=self.request, environ=environ)

    def _get_response(self, objtype=None):
        return self._response

    def _set_response(self, response):
        if isinstance(response, unicode):
            self._response.unicode_body = response
        elif isinstance(response, str):
            self._response.body = response
        elif isinstance(response, BaseResponse):
            self._response = response
        else:
            raise ValueError('Excpected `Response` or `basestring` object.')

    response = property(_get_response, _set_response)

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    def __call__(self, view_func, **view_args):
        with self:
            self.response = view_func(self, **view_args)
        return self.request.call_application(self.response)



Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
# -*- coding: utf-8 -*-

'''
    livestreetcms.wrappers
    ~~~~~~~~~~~~~~~~~~~~~~
    
    
'''

from webob import Request as BaseRequest
from webob import Response as BaseResponse


class Request(BaseRequest):
    '''Request class
    '''

    def __init__(self, *argv, **kw): 
        super(Request, self).__init__(*argv, **kw)
        if self.charset is None:
            self.charset = 'utf-8'


class Response(BaseResponse):
    '''Response class
    '''



Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
class Interface(object):
    """Marker base class for extension point interfaces."""


class ExtensionPoint(property):
    """Marker class for extension points in components."""

    def __init__(self, interface):
        """Create the extension point.
        
        @param interface: the `Interface` subclass that defines the protocol
            for the extension point
        """
        property.__init__(self, self.extensions)
        self.interface = interface
        self.__doc__ = 'List of components that implement `%s`' % \
                       self.interface.__name__

    def extensions(self, component):
        """Return a list of components that declare to implement the extension
        point interface."""
        extensions = ComponentMeta._registry.get(self.interface, [])
        return filter(None, [component.compmgr[cls] for cls in extensions])

    def __repr__(self):
        """Return a textual representation of the extension point."""
        return '<ExtensionPoint %s>' % self.interface.__name__


class ComponentMeta(type):
    """Meta class for components.
    
    Takes care of component and extension point registration.
    """
    _components = []
    _registry = {}

    def __new__(cls, name, bases, d):
        """Create the component class."""

        d['_implements'] = _implements[:]
        del _implements[:]

        new_class = type.__new__(cls, name, bases, d)
        if name == 'Component':
            # Don't put the Component base class in the registry
            return new_class

        # Only override __init__ for Components not inheriting ComponentManager
        if True not in [issubclass(x, ComponentManager) for x in bases]:
            # Allow components to have a no-argument initializer so that
            # they don't need to worry about accepting the component manager
            # as argument and invoking the super-class initializer
            init = d.get('__init__')
            if not init:
                # Because we're replacing the initializer, we need to make sure
                # that any inherited initializers are also called.
                for init in [b.__init__._original for b in new_class.mro()
                             if issubclass(b, Component)
                             and '__init__' in b.__dict__]:
                    break
            def maybe_init(self, compmgr, init=init, cls=new_class):
                if cls not in compmgr.components:
                    compmgr.components[cls] = self
                    if init:
                        init(self)
            maybe_init._original = init
            new_class.__init__ = maybe_init

        if d.get('abstract'):
            # Don't put abstract component classes in the registry
            return new_class

        ComponentMeta._components.append(new_class)
        registry = ComponentMeta._registry
        for interface in d.get('_implements', []):
            registry.setdefault(interface, []).append(new_class)
        for base in [base for base in bases if hasattr(base, '_implements')]:
            for interface in base._implements:
                registry.setdefault(interface, []).append(new_class)

        return new_class


_implements = []

def implements(*interfaces):
    """Can be used in the class definiton of `Component` subclasses to declare
    the extension points that are extended.
    """
    _implements.extend(interfaces)


class Component(object):
    """Base class for components.

    Every component can declare what extension points it provides, as well as
    what extension points of other components it extends.
    """
    __metaclass__ = ComponentMeta

    def __new__(cls, *args, **kwargs):
        """Return an existing instance of the component if it has already been
        activated, otherwise create a new instance.
        """
        # If this component is also the component manager, just invoke that
        if issubclass(cls, ComponentManager):
            self = super(Component, cls).__new__(cls)
            self.compmgr = self
            return self

        # The normal case where the component is not also the component manager
        compmgr = args[0]
        self = compmgr.components.get(cls)
        if self is None:
            self = super(Component, cls).__new__(cls)
            self.compmgr = compmgr
            compmgr.component_activated(self)
        return self


class ComponentManager(object):
    """The component manager keeps a pool of active components."""

    def __init__(self):
        """Initialize the component manager."""
        self.components = {}
        self.enabled = {}
        if isinstance(self, Component):
            self.components[self.__class__] = self

    def __contains__(self, cls):
        """Return wether the given class is in the list of active components."""
        return cls in self.components

    def __getitem__(self, cls):
        """Activate the component instance for the given class, or return the
        existing the instance if the component has already been activated."""
        if cls not in self.enabled:
            self.enabled[cls] = self.is_component_enabled(cls)
        if not self.enabled[cls]:
            return None
        component = self.components.get(cls)
        if not component:
            if cls not in ComponentMeta._components:
                raise Exception('Component "%s" not registered' % cls.__name__)
            try:
                component = cls(self)
            except TypeError, e:
                raise Exception('Unable to instantiate component %r (%s)' %
                                (cls, e))
        return component

    def component_activated(self, component):
        """Can be overridden by sub-classes so that special initialization for
        components can be provided.
        """

    def is_component_enabled(self, cls):
        """Can be overridden by sub-classes to veto the activation of a
        component.

        If this method returns False, the component with the given class will
        not be available.
        """
        return True




wsgi application
Код: python
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
import os
from webob.exc import HTTPException

from app.context import ControllerContext
from app.component import ComponentManager, Component

class WSGIApplicationInstance(Component, ComponentManager):

    def __init__(self):
        super(WSGIApplicationInstance, self).__init__()
      
    

class WSGIApplication(object):


    def __init__(self, project_dir):
        
        self.instance = WSGIApplicationInstance()

    def wsgi_app(self, environ, start_response):
        context = ControllerContext(self.instance, environ)
        context.response = 'Hello Word! '
        return context.response(environ, start_response)

    def __call__(self, environ, start_response):
       return self.wsgi_app(environ, start_response)



...
Рейтинг: 0 / 0
[Python] wsgi приложение
    #37954460
Viktoria2792
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Спасибо! Очень всем благодарна! Теперь успеваю сдать все вовремя.)
...
Рейтинг: 0 / 0
Период между сообщениями больше года.
[Python] wsgi приложение
    #38861404
amigo_george
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Viktoria2792, расскажите пожалуйста о Вашем решении.
...
Рейтинг: 0 / 0
12 сообщений из 12, страница 1 из 1
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / [Python] wsgi приложение
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]