本文整理汇总了Python中model.Model.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Model.connect方法的具体用法?Python Model.connect怎么用?Python Model.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类model.Model
的用法示例。
在下文中一共展示了Model.connect方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
def run(self):
print 'running Daemon'
# check that it has all of the needed fields
if all([i in config for i in ('model','database','fields')]):
print 'its got all the needed fields'
else:
print 'youre missing some important fields... make sure you have model, database, and fields'
raise Exception('Config file missing item')
m = Model(self.config['model'])
m.connect(**self.config['database'])
latest = m.getlatesttime()
args = {}
if 'geos' in config:
args['geos'] = config['geos']
else:
args['geos'] = None
if 'pressure' in config:
args['pressure'] = config['pressure']
else:
args['pressure'] = None
if 'calculatedfields' in config:
print config
for field in config['calculatedfields']:
for key, value in field.items():
m.addcalculatedfield(key,value['dependents'],value['calculation'])
ntries = 0
ntriesmax = max(int(config['modelint']/config['poll']*2/3),1)
print "We'll try each download up to four times."
while True:
starttime = time.time()
url = m._createurl(latest)
check = m._checkurl(url)
if check:
print 'The new data is available! Downloading ...'
try:
if ntries < ntriesmax:
ntries = ntries+1
m.transfer(config['fields'],latest,**args)
latest = latest + datetime.timedelta(seconds=self.config['modelint'])
ntries = 0
except:
print 'An error occured in downloading the data... it might not actually be available'
print 'The next run will happen at %s' % latest
else:
print 'No new data. Sad face'
endtime = time.time()
pausetime = max(
config['poll'] - ( endtime - starttime ),
0
)
print 'Pausing for %d seconds' % pausetime
time.sleep(pausetime)
示例2: Client
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
class Client(object):
def __init__(self):
self.app = Qt.QApplication(sys.argv)
self.__authWidget = AuthorizationWidget(self.authValidator)
self.__view = View(self.app)
self.__authWidget.show()
self.app.exec_()
def authValidator(self, login, password, server):
if login == "":
return "login is empty"
if password == "":
return "password is empty"
if login.replace(' ', '') == "":
return "login contains only spaces"
if server == "vkmessenger.com":
login += "@vk.com"
else:
if server == "gmail.com":
login += "@gmail.com"
else:
if server == "localhost":
login += "@localhost.ru"
self.__model = Model()
self.__view.setModel(self.__model)
self.__model.setView(self.__view)
if self.__model.auth(login, password, server):
self.__model.connect(login, password, server)
else:
return "login or password is invalid"
self.__authWidget.close()
self.__view.show()
return True
示例3: WebActivity
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
class WebActivity(activity.Activity):
def __init__(self, handle):
activity.Activity.__init__(self, handle)
_logger.debug('Starting the web activity')
session = WebKit.get_default_session()
session.set_property('accept-language-auto', True)
session.set_property('ssl-use-system-ca-file', True)
session.set_property('ssl-strict', False)
# By default, cookies are not stored persistently, we have to
# add a cookie jar so that they get saved to disk. We use one
# with a SQlite database:
cookie_jar = SoupGNOME.CookieJarSqlite(filename=_cookies_db_path,
read_only=False)
session.add_feature(cookie_jar)
_seed_xs_cookie(cookie_jar)
# FIXME
# downloadmanager.remove_old_parts()
self._force_close = False
self._tabbed_view = TabbedView()
self._tabbed_view.connect('focus-url-entry', self._on_focus_url_entry)
self._tabbed_view.connect('switch-page', self.__switch_page_cb)
self._tray = HTray()
self.set_tray(self._tray, Gtk.PositionType.BOTTOM)
self._primary_toolbar = PrimaryToolbar(self._tabbed_view, self)
self._edit_toolbar = EditToolbar(self)
self._view_toolbar = ViewToolbar(self)
self._primary_toolbar.connect('add-link', self._link_add_button_cb)
self._primary_toolbar.connect('go-home', self._go_home_button_cb)
self._primary_toolbar.connect('go-library', self._go_library_button_cb)
self._primary_toolbar.connect('set-home', self._set_home_button_cb)
self._primary_toolbar.connect('reset-home', self._reset_home_button_cb)
self._edit_toolbar_button = ToolbarButton(
page=self._edit_toolbar, icon_name='toolbar-edit')
self._primary_toolbar.toolbar.insert(
self._edit_toolbar_button, 1)
view_toolbar_button = ToolbarButton(
page=self._view_toolbar, icon_name='toolbar-view')
self._primary_toolbar.toolbar.insert(
view_toolbar_button, 2)
self._primary_toolbar.show_all()
self.set_toolbar_box(self._primary_toolbar)
self.set_canvas(self._tabbed_view)
self._tabbed_view.show()
self.model = Model()
self.model.connect('add_link', self._add_link_model_cb)
self.connect('key-press-event', self._key_press_cb)
if handle.uri:
self._tabbed_view.current_browser.load_uri(handle.uri)
elif not self._jobject.file_path:
# TODO: we need this hack until we extend the activity API for
# opening URIs and default docs.
self._tabbed_view.load_homepage()
self.messenger = None
self.connect('shared', self._shared_cb)
# Get the Presence Service
self.pservice = presenceservice.get_instance()
try:
name, path = self.pservice.get_preferred_connection()
self.tp_conn_name = name
self.tp_conn_path = path
self.conn = telepathy.client.Connection(name, path)
except TypeError:
_logger.debug('Offline')
self.initiating = None
if self.get_shared_activity() is not None:
_logger.debug('shared: %s', self.get_shared())
# We are joining the activity
_logger.debug('Joined activity')
self.connect('joined', self._joined_cb)
if self.get_shared():
# We've already joined
self._joined_cb()
else:
_logger.debug('Created activity')
# README: this is a workaround to remove old temp file
#.........这里部分代码省略.........
示例4: __init__
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
#.........这里部分代码省略.........
elt = None
if t.strip() != "":
if is_url(t):
elt = Url(is_url(t), [])
elif is_hostname(t):
elt = Hostname(is_hostname(t), [])
elif is_ip(t):
elt = Ip(is_ip(t), [])
if elt:
added.append(self.save_element(elt, tags))
if len(added) == 1:
return added[0]
else:
return added
def save_element(self, element, tags=[], with_status=False):
element.upgrade_tags(tags)
return self.data.save(element, with_status=with_status)
# graph function
def add_artifacts(self, data, tags=[]):
artifacts = find_artifacts(data)
added = []
for url in artifacts['urls']:
added.append(self.save_element(url, tags))
for hostname in artifacts['hostnames']:
added.append(self.save_element(hostname, tags))
for ip in artifacts['ips']:
added.append(self.save_element(ip, tags))
return added
# elements analytics
def bulk_asn(self, items=1000):
last_analysis = {'$or': [
{ 'last_analysis': {"$lt": datetime.datetime.utcnow() - datetime.timedelta(days=7)} },
{ 'last_analysis': None },
]
}
nobgp = {"$or": [{'bgp': None}, last_analysis ]}
total = self.data.elements.find({ "$and": [{'type': 'ip'}, nobgp]}).count()
done = 0
results = [r for r in self.data.elements.find({ "$and": [{'type': 'ip'}, nobgp]})[:items]]
while len(results) > 0:
ips = []
debug_output("(getting ASNs for %s IPs - %s/%s done)" % (len(results), done, total), type='analytics')
for r in results:
ips.append(r)
as_info = {}
try:
as_info = get_net_info_shadowserver(ips)
except Exception, e:
debug_output("Could not get AS for IPs: %s" % e)
if as_info == {}:
debug_output("as_info empty", 'error')
return
for ip in as_info:
_as = as_info[ip]
_ip = self.data.find_one({'value': ip})
if not _ip:
return
del _as['ip']
for key in _as:
if key not in ['type', 'value', 'tags']:
_ip[key] = _as[key]
del _as['bgp']
_as = As.from_dict(_as)
# commit any changes to DB
_as = self.save_element(_as)
_ip = self.save_element(_ip)
if _as and _ip:
self.data.connect(_ip, _as, 'net_info')
done += len(results)
results = [r for r in self.data.elements.find({ "$and": [{'type': 'ip'}, nobgp]})[:items]]
示例5: WebActivity
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
class WebActivity(activity.Activity):
def __init__(self, handle):
activity.Activity.__init__(self, handle)
_logger.debug('Starting the web activity')
# figure out if we're an SSB
self.is_ssb = ssb.get_is_ssb(self)
self._browser = Browser()
_set_accept_languages()
_seed_xs_cookie()
_set_dbus_globals(self.get_bundle_id())
# don't pick up the sugar theme - use the native mozilla one instead
cls = components.classes['@mozilla.org/preferences-service;1']
pref_service = cls.getService(components.interfaces.nsIPrefService)
branch = pref_service.getBranch("mozilla.widget.")
branch.setBoolPref("disable-native-theme", True)
toolbox = activity.ActivityToolbox(self)
self._edit_toolbar = EditToolbar(self._browser)
toolbox.add_toolbar(_('Edit'), self._edit_toolbar)
self._edit_toolbar.show()
self._web_toolbar = WebToolbar(self)
toolbox.add_toolbar(_('Browse'), self._web_toolbar)
self._web_toolbar.show()
self._tray = HTray()
self.set_tray(self._tray, gtk.POS_BOTTOM)
self._tray.show()
self._view_toolbar = ViewToolbar(self)
toolbox.add_toolbar(_('View'), self._view_toolbar)
self._view_toolbar.show()
# the bookmarklet bar doesn't show up if empty
self._bm_toolbar = None
self.set_toolbox(toolbox)
toolbox.show()
self.set_canvas(self._browser)
self._browser.show()
self._browser.history.connect('session-link-changed',
self._session_history_changed_cb)
self._web_toolbar.connect('add-link', self._link_add_button_cb)
self._browser.connect("notify::title", self._title_changed_cb)
self._bm_store = bookmarklets.get_store()
self._bm_store.connect('add_bookmarklet', self._add_bookmarklet_cb)
self._bm_store.connect('overwrite_bookmarklet',
self._overwrite_bookmarklet_cb)
for name in self._bm_store.list():
self._add_bookmarklet(name)
self.model = Model()
self.model.connect('add_link', self._add_link_model_cb)
self.current = _('blank')
self.webtitle = _('blank')
self.connect('key-press-event', self._key_press_cb)
self.toolbox.set_current_toolbar(_TOOLBAR_BROWSE)
if self.is_ssb:
# set permanent homepage for SSBs
f = open(os.path.join(activity.get_bundle_path(),
'data/homepage'))
self.homepage = f.read()
f.close()
# enable userscript saving
self._browser.userscript.connect('userscript-found',
self._userscript_found_cb)
# enable userscript injecting
self._browser.userscript.connect('userscript-inject',
self._userscript_inject_cb)
if handle.uri:
self._browser.load_uri(handle.uri)
elif not self._jobject.file_path:
# TODO: we need this hack until we extend the activity API for
# opening URIs and default docs.
self._load_homepage()
self.messenger = None
self.connect('shared', self._shared_cb)
# Get the Presence Service
self.pservice = presenceservice.get_instance()
try:
name, path = self.pservice.get_preferred_connection()
self.tp_conn_name = name
self.tp_conn_path = path
#.........这里部分代码省略.........
示例6:
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
from application import app
from model import Model
Model.connect('cookiemonster.sqlite')
app.run(debug=True)
示例7: range
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
import sqlite3
from model import Model
from cookie import Cookie
from distributor import Distributor
from warehouse import Warehouse
from buyer import Buyer
from transaction import Transaction
from order import Order
from purchase import Purchase
from random import randint
Model.connect('CookieMonster.sqlite')
conn = Model.conn
cursor = Model.cursor
cursor.execute('DELETE FROM cookies')
cursor.execute('DELETE FROM distributors')
cursor.execute('DELETE FROM warehouses')
cursor.execute('DELETE FROM buyers')
cursor.execute('DELETE FROM buyer_orders')
cursor.execute('DELETE FROM purchases')
cursor.execute('DELETE FROM stock')
cursor.execute('DELETE FROM transactions')
#create cookies
for i in range(5):
Cookie("Cookie" + str(i), 1.99).save()
#create distributors
for i in range(5):
Distributor("Distributor" + str(i), "Somewhereville").save()
示例8: __init__
# 需要导入模块: from model import Model [as 别名]
# 或者: from model.Model import connect [as 别名]
class Analytics:
def __init__(self, max_threads=4):
self.data = Model()
#self.max_threads = threading.Semaphore(app.config['THREADS'])
self.active = False
self.websocket = None
self.thread = None
self.websocket_lock = threading.Lock()
self.progress = 0
self.total = 0
self.max_threads = threading.Semaphore(4)
def add_text(self, text, context=[]):
added = []
for t in text:
elt = None
if t.strip() != "":
if is_ip(t):
elt = Ip(is_ip(t), [])
elif is_url(t):
elt = Url(is_url(t), [])
elif is_hostname(t):
elt = Hostname(is_hostname(t), [])
if elt:
added.append(self.save_element(elt, context))
if len(added) == 1:
return added[0]
else:
return added
def save_element(self, element, context=[], with_status=False):
element.upgrade_context(context)
return self.data.save(element, with_status=with_status)
# graph function
def add_artifacts(self, data, context=[]):
artifacts = find_artifacts(data)
added = []
for url in artifacts['urls']:
added.append(self.data.save(url, context))
for hostname in artifacts['hostnames']:
added.append(self.data.hostname_add(hostname, context))
for ip in artifacts['ips']:
added.append(self.data.ip_add(ip, context))
return added
# elements analytics
def bulk_asn(self):
results = self.data.elements.find({ 'type': 'ip' })
#elts = []
ips = []
debug_output("(getting ASNs for %s IPs)" % results.count(), type='analytics')
for r in results:
ips.append(r)
as_info = get_net_info_shadowserver(ips)
if not as_info:
return
for ip in as_info:
_as = as_info[ip]
_ip = self.data.find_one({'value': ip})
del _as['ip']
for key in _as:
if key not in ['type', 'value', 'context']:
_ip[key] = _as[key]
del _as['bgp']
_as = As.from_dict(_as)
# commit any changes to DB
_as = self.save_element(_as)
_ip = self.save_element(_ip)
if _as and _ip:
self.data.connect(_ip, _as, 'net_info')
def find_evil(self, elt, depth=2, node_links=([],[])):
evil_nodes = []
evil_links = []
#.........这里部分代码省略.........