code
stringlengths 2
1.05M
| repo_name
stringlengths 5
104
| path
stringlengths 4
251
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^project/', include('project.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/(.*)', admin.site.root),
)
|
na/django-metatags
|
project/urls.py
|
Python
|
mit
| 533
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blogg', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('content', models.TextField(max_length=1000L)),
('author', models.CharField(default=b'Anonymous', max_length=100, blank=True)),
('ip_address', models.GenericIPAddressField(null=True, blank=True)),
('user_agent', models.CharField(max_length=500L, blank=True)),
('published', models.BooleanField(default=True)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True, auto_now_add=True)),
('post', models.ForeignKey(related_name='comments', to='blogg.Post')),
],
options={
'ordering': ['-created'],
},
bases=(models.Model,),
),
]
|
ishahid/django-blogg
|
source/blogg/migrations/0002_comment.py
|
Python
|
mit
| 1,206
|
from .path import Path
class Morphism(object):
def __init__(self, arrows):
self.arrows = arrows
def __call__(self, domain):
codomain = {}
for arrow in self.arrows:
codomain = arrow.apply(domain, codomain)
return codomain
@classmethod
def compile(cls, *expressions, **kwargs):
ctx = kwargs.pop('ctx', {})
arrows = [Arrow.parse(expr, ctx=ctx) for expr in expressions]
return cls(arrows)
class Arrow(object):
symbol = '->'
def __init__(self, source_paths, function, destination_path):
self.source_paths = source_paths
self.function = function
self.destination_path = destination_path
@classmethod
def parse(cls, representation, ctx=None):
tokens = map(str.strip, representation.split(cls.symbol))
destination_path = Path.parse(tokens.pop())
source_paths = []
callable_tokens = []
for token in tokens:
if token[0] == '/':
source_paths.append(Path.parse(token))
else:
callable_tokens.append(token)
callables = []
for token in callable_tokens:
if token in ctx:
callables.append(ctx[token])
elif token.startswith('py::'):
try:
python_function = eval(token[4:])
if not callable(python_function):
raise Exception(
'Token %s is not a callable in expression %s' %
(token, representation)
)
callables.append(python_function)
except Exception as e:
raise Exception(
'Failed to parse token %s in expression %s' %
(token, representation)
)
function = cls.compose(*callables)
return cls(source_paths, function, destination_path)
def apply(self, domain, codomain):
inputs = [path.resolve(domain) for path in self.source_paths]
input_ = inputs[0] if len(inputs) == 1 else tuple(inputs)
destination_value = self.function(input_)
return self.destination_path.set(codomain, destination_value)
@classmethod
def compose(cls, *functions):
def inner(arg):
for f in functions:
arg = f(arg)
return arg
return inner
|
cieplak/morf
|
morf/morphism.py
|
Python
|
mit
| 2,478
|
import gamerocket
from flask import Flask, request, render_template
app = Flask(__name__)
gamerocket.Configuration.configure(gamerocket.Environment.Development,
apiKey = "your_apiKey",
secretKey = "your_secretKey")
@app.route("/")
def form():
return render_template("form.html")
@app.route("/create_player", methods=["POST"])
def create_player():
result = gamerocket.Player.create({
"name":request.form["name"],
"locale":request.form["locale"]
})
if result.is_success:
return "<h1>Success! Player ID: " + result.player.id + "</h1>"
else:
return "<h1>Error " + result.error + ": " + result.error_description + "</h1>"
if __name__ == '__main__':
app.run(debug=True)
|
workbandits/gamerocket-python-guide
|
1_create_player/src/app.py
|
Python
|
mit
| 837
|
#-*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django.db import IntegrityError
from spirit.signals.comment import comment_posted
from spirit.signals.topic_private import topic_private_post_create, topic_private_access_pre_create
from spirit.signals.topic import topic_viewed
from spirit.managers.topic_notifications import TopicNotificationManager
UNDEFINED, MENTION, COMMENT = xrange(3)
ACTION_CHOICES = (
(UNDEFINED, _("Undefined")),
(MENTION, _("Mention")),
(COMMENT, _("Comment")),
)
class TopicNotification(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("user"))
topic = models.ForeignKey('spirit.Topic')
comment = models.ForeignKey('spirit.Comment', null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
action = models.IntegerField(choices=ACTION_CHOICES, default=UNDEFINED)
is_read = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = TopicNotificationManager()
class Meta:
app_label = 'spirit'
unique_together = ('user', 'topic')
ordering = ['-date', ]
verbose_name = _("topic notification")
verbose_name_plural = _("topics notification")
def get_absolute_url(self):
return self.comment.get_absolute_url()
@property
def text_action(self):
return ACTION_CHOICES[self.action][1]
@property
def is_mention(self):
return self.action == MENTION
@property
def is_comment(self):
return self.action == COMMENT
def __unicode__(self):
return "%s in %s" % (self.user, self.topic)
def notification_comment_posted_handler(sender, comment, **kwargs):
# Create Notification for poster
# if not exists create a dummy one with defaults
try:
TopicNotification.objects.get_or_create(user=comment.user, topic=comment.topic,
defaults={'action': COMMENT,
'is_read': True,
'is_active': True})
except IntegrityError:
pass
TopicNotification.objects.filter(topic=comment.topic, is_active=True, is_read=True)\
.exclude(user=comment.user)\
.update(comment=comment, is_read=False, action=COMMENT, date=timezone.now())
def mention_comment_posted_handler(sender, comment, mentions, **kwargs):
if not mentions:
return
for username, user in mentions.iteritems():
try:
TopicNotification.objects.create(user=user, topic=comment.topic,
comment=comment, action=MENTION)
except IntegrityError:
pass
TopicNotification.objects.filter(user__in=mentions.values(), topic=comment.topic, is_read=True)\
.update(comment=comment, is_read=False, action=MENTION, date=timezone.now())
def comment_posted_handler(sender, comment, mentions, **kwargs):
notification_comment_posted_handler(sender, comment, **kwargs)
mention_comment_posted_handler(sender, comment, mentions, **kwargs)
def topic_private_post_create_handler(sender, topics_private, comment, **kwargs):
# topic.user notification is created on comment_posted
TopicNotification.objects.bulk_create([TopicNotification(user=tp.user, topic=tp.topic,
comment=comment, action=COMMENT,
is_active=True)
for tp in topics_private
if tp.user != tp.topic.user])
def topic_private_access_pre_create_handler(sender, topic, user, **kwargs):
# TODO: use update_or_create on django 1.7
# change to post create
try:
TopicNotification.objects.create(user=user, topic=topic,
comment=topic.comment_set.last(), action=COMMENT,
is_active=True)
except IntegrityError:
pass
def topic_viewed_handler(sender, request, topic, **kwargs):
if not request.user.is_authenticated():
return
TopicNotification.objects.filter(user=request.user, topic=topic)\
.update(is_read=True)
comment_posted.connect(comment_posted_handler, dispatch_uid=__name__)
topic_private_post_create.connect(topic_private_post_create_handler, dispatch_uid=__name__)
topic_private_access_pre_create.connect(topic_private_access_pre_create_handler, dispatch_uid=__name__)
topic_viewed.connect(topic_viewed_handler, dispatch_uid=__name__)
|
bjorncooley/rainforest_makers
|
spirit/models/topic_notification.py
|
Python
|
mit
| 4,847
|
user_input = raw_input()
class Taowa:
def __init__(self):
return
def setSize(self, m1, m2):
self.width = m1
self.height = m2
self.area = m1 * m2
class Sorter:
def __init__(self):
self.taowas = []
self.lastWidth = 0
self.lastHeight = 0
return
def setArray(self, str):
self.arr = str.split(' ')
for idx in range(len(self.arr)):
self.arr[idx] = int(self.arr[idx])
def makeTaowa(self):
l = len(self.arr) / 2
for idx in range(l):
m1 = self.arr[idx*2]
m2 = self.arr[idx*2+1]
taowa = Taowa()
taowa.setSize(m1, m2)
self.taowas.append(taowa)
def sortTaowa(self):
self.taowas.sort(key=lambda taowa:taowa.width)
def calculate(self):
l = len(self.taowas)
self.lastHeight = self.taowas[0].height
self.lastWidth = self.taowas[0].width
m = 1
for idx in range(1, l, 1):
taowa = self.taowas[idx]
w = taowa.width
h = taowa.height
if w > self.lastWidth and h > self.lastHeight :
m = m+1
self.lastWidth = w
self.lastHeight = h
return m
sorter = Sorter()
sorter.setArray(user_input)
sorter.makeTaowa()
sorter.sortTaowa()
user_input = sorter.calculate()
print user_input
|
zxgaoray/calculate_play
|
calculator/Taowa.py
|
Python
|
mit
| 1,409
|
from django.views.generic.detail import DetailView
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views import generic
from django.views.generic.edit import DeleteView, CreateView, UpdateView
from .forms import BandForm, ArchivForm, InstitutionForm, PersonForm, BearbeiterForm
from .models import Band, Archiv, Institution, Person, Bearbeiter
class BearbeiterListView(generic.ListView):
model = Bearbeiter
template_name = 'entities/bearbeiter_list.html'
context_object_name = 'object_list'
class BearbeiterDetailView(DetailView):
model = Bearbeiter
class BearbeiterCreate(CreateView):
model = Bearbeiter
template_name_suffix = '_create'
form_class = BearbeiterForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BearbeiterCreate, self).dispatch(*args, **kwargs)
class BearbeiterUpdate(UpdateView):
model = Bearbeiter
template_name_suffix = '_create'
form_class = BearbeiterForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BearbeiterUpdate, self).dispatch(*args, **kwargs)
class BearbeiterDelete(DeleteView):
model = Bearbeiter
template_name = 'vocabs/confirm_delete.html'
success_url = reverse_lazy('browsing:browse_bearbeiter')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BearbeiterDelete, self).dispatch(*args, **kwargs)
class PersonListView(generic.ListView):
model = Person
template_name = 'entities/band_list.html'
context_object_name = 'object_list'
class PersonDetailView(DetailView):
model = Person
class PersonCreate(CreateView):
model = Person
template_name_suffix = '_create'
form_class = PersonForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(PersonCreate, self).dispatch(*args, **kwargs)
class PersonUpdate(UpdateView):
model = Person
template_name_suffix = '_create'
form_class = PersonForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(PersonUpdate, self).dispatch(*args, **kwargs)
class PersonDelete(DeleteView):
model = Person
template_name = 'vocabs/confirm_delete.html'
success_url = reverse_lazy('browsing:browse_persons')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(PersonDelete, self).dispatch(*args, **kwargs)
class BandListView(generic.ListView):
model = Band
template_name = 'entities/band_list.html'
context_object_name = 'object_list'
def get_queryset(self):
return Band.objects.order_by('signatur')
class BandDetailView(DetailView):
model = Band
class BandCreate(CreateView):
model = Band
template_name_suffix = '_create'
form_class = BandForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BandCreate, self).dispatch(*args, **kwargs)
class BandUpdate(UpdateView):
model = Band
template_name_suffix = '_create'
form_class = BandForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BandUpdate, self).dispatch(*args, **kwargs)
class BandDelete(DeleteView):
model = Band
template_name = 'vocabs/confirm_delete.html'
success_url = reverse_lazy('browsing:browse_baende')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BandDelete, self).dispatch(*args, **kwargs)
# Archiv
class ArchivDetailView(DetailView):
model = Archiv
class ArchivCreate(CreateView):
model = Archiv
template_name_suffix = '_create'
form_class = ArchivForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ArchivCreate, self).dispatch(*args, **kwargs)
class ArchivUpdate(UpdateView):
model = Archiv
template_name_suffix = '_create'
form_class = ArchivForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ArchivUpdate, self).dispatch(*args, **kwargs)
class ArchivDelete(DeleteView):
model = Archiv
template_name = 'vocabs/confirm_delete.html'
success_url = reverse_lazy('browsing:browse_archivs')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ArchivDelete, self).dispatch(*args, **kwargs)
# Institution
class InstitutionDetailView(DetailView):
model = Institution
class InstitutionCreate(CreateView):
model = Institution
template_name_suffix = '_create'
form_class = InstitutionForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(InstitutionDelete, self).dispatch(*args, **kwargs)
class InstitutionUpdate(UpdateView):
model = Institution
template_name_suffix = '_create'
form_class = InstitutionForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(InstitutionUpdate, self).dispatch(*args, **kwargs)
class InstitutionDelete(DeleteView):
model = Institution
template_name = 'vocabs/confirm_delete.html'
success_url = reverse_lazy('browsing:browse_institutions')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(InstitutionDelete, self).dispatch(*args, **kwargs)
|
acdh-oeaw/vhioe
|
entities/views.py
|
Python
|
mit
| 5,608
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0004_make_focal_point_key_not_nullable'),
('wagtailcore', '0008_populate_latest_revision_created_at'),
]
operations = [
migrations.CreateModel(
name='HomePage',
fields=[
('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('video', models.URLField(null=True, verbose_name='Background Video')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='Office',
fields=[
('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('official', models.CharField(max_length=30, null=True, verbose_name="Official's Name")),
('phone', models.CharField(max_length=15, null=True, verbose_name='Phone')),
('address', models.TextField(null=True, verbose_name='Address')),
('body', models.TextField(null=True, verbose_name='Page Body')),
('portrait', models.ForeignKey(verbose_name='Portrait', to='wagtailimages.Image', null=True)),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='OfficePage',
fields=[
('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('body', models.TextField(null=True, verbose_name='Page Body')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='Offices',
fields=[
('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
|
morgan-county/site
|
morgan/apps/cms/migrations/0001_initial.py
|
Python
|
mit
| 2,452
|
"""
Methods to get certain kinds of data from the Github API.
Writes each repo's data to a separate file in a given directory
"""
import json
from mimetools import Message
from StringIO import StringIO
from github_util import *
import time
import sys, os
#####
# CONSTANTS
#####
#constants to specify parameters when calling methods
CONTRIBUTORS = 0
FORKERS = 1
#DOES NOT WORK UNLESS YOU HAVE PUSH ACCESS
COLLABORATORS = 10
#the url path to the information in the api
URL_PATH = {CONTRIBUTORS:'contributors', COLLABORATORS:'collaborators', FORKERS:'forks'}
#the path to the following information in the json
JSON_PATH = {CONTRIBUTORS:('login',), COLLABORATORS:('login',), FORKERS:('owner', 'login')}
#####
# METHODS
#####
"""
Gets all the repos of the users
Returns dictionary {user:reponamelist}
or if forks is True, returns {user:(nonforknamelist, forknamelist)}
"""
def get_repos(users, forks=False):
#a dictionary to store all the {users:repos}
all_repos = {}
for u in users:
repos = []
forked = []
page = 1
while page>0: #api has multiple pages
URLstr = 'https://api.github.com/users/{}/repos'.format(u)
response = api_get(URLstr, parameters={'page':page, 'per_page':100})
if not is_successful_response(response):
print "{}\n{}\n{}\n".format(URLstr, response.status_code, response.text)
break
if has_next_page(response):
page += 1
else:
page = -1
#read the data of the current page
try:
repo_data = json.loads(response.text)
except:
error_dump("{}\n{}\n{}".format(response, URLstr, response.text))
raise e
for repo in repo_data:
#get name of the repo
repoName = JSON_access(repo, ('name',))
#split forks and non-forks, if necessary
isFork = JSON_access(repo, ('fork',))
if forks and isFork:
forked.append(repoName)
else:
repos.append(repoName)
#add to the allRepos dictionary
if forks:
all_repos[u] = (repos,forked)
else:
all_repos[u] = repos
return all_repos
"""
grabs a list of all (contributors|collaborators|forkers) of all the repos
returns a dict of {repo_name : list of people}
"""
def repoPeople(repo_list,group=CONTRIBUTORS):
all_repos = {}
for repo in repo_list:
people = []
page = 1
while page>0:
URLstr = 'https://api.github.com/repos/{}/{}/{}'.format(repo["user"], repo["name"], URL_PATH[group])
response = api_get(baseURL=URLstr, parameters={'page':page,'per_page':100})
if not is_successful_response(response):
print "{}\n{}\n{}\n".format(URLstr, response.status_code, response.text)
break
if has_next_page(response):
page += 1
else:
page = -1
try:
responsePage = json.loads(response.text)
except:
error_dump("{}\n{}\n{}".format(response, URLstr, response.text))
raise e
for contributor in responsePage:
username = JSON_access(contributor, JSON_PATH[group])
if username != None:
people.append(username)
all_repos[repo["name"]] = people
return all_repos
"""
Gets all the pull requests for a repo
"""
def get_pulls(repo):
URLstr = "https://api.github.com/repos/{}/{}/pulls".format(repo["user"], repo["name"])
page = 1
pulls = []
while page>0:
response = api_get(baseURL=URLstr, parameters={'page':page, 'per_page':100, "state":"all"})
if not is_successful_response(response):
print "{}\n{}\n{}\n".format(URLstr, response.status_code, response.text)
break
if has_next_page(response):
page += 1
else:
page = -1
try:
responsePage = json.loads(response.text)
except:
error_dump("{}\n{}\n{}".format(response, URLstr, response.text))
raise e
pulls.extend(responsePage)
return pulls
"""
check if a repo is forked, and if so, return the parent repo in a tuple (reponame, ownername)
else, return None
"""
def parent_repo(repo,user):
URLstr = "https://api.github.com/repos/{}/{}".format(user, repo)
response = api_get(baseURL=URLstr)
if not is_successful_response(response):
print "{}\n{}\n{}\n".format(URLstr, response.status_code, response.text)
return None
page = json.loads(response.text)
parentRepo = None
if JSON_access(page, ('fork',)):
name = JSON_access(page,('parent','name'))
owner = JSON_access(page, ('parent','owner','login'))
if name != None and owner != None:
parentRepo = (name, owner)
return parentRepo
"""
Returns all the commits of a given repo
"""
def get_all_commits(repo):
URLstr = "https://api.github.com/repos/{}/{}/commits".format(repo["user"], repo["name"])
commits = []
page = 1
while page>0:
response = api_get(baseURL=URLstr, parameters={'page':page,'per_page':100})
if not is_successful_response(response):
print "{}\n{}\n{}\n".format(URLstr, response.status_code, response.text)
break
if has_next_page(response):
page += 1
else:
page = -1
try:
responsePage = json.loads(response.text)
except:
error_dump("{}\n{}\n{}".format(response, URLstr, response.text))
raise e
commits.extend(responsePage)
return commits
#####
# TESTS
# make sure I didn't break anything
#####
if __name__=='__main__':
print parent_repo('ReadingJournal', 'poosomooso')
print parent_repo('QingTingCheat', "felixonmars") #should return None and print error because DMCA takedown
print repoPeople([{"name":'EmptyTest', "user":'poosomooso'}], group=CONTRIBUTORS) #print error code and also empty list in dict
print repoPeople([{"name":'Codestellation2015', "user":'IanOlin'}], group=CONTRIBUTORS)
print get_repos(("poosomooso", ))
repos = get_repos(("sindresorhus", )) #guy's got a lot of repos
print len(repos["sindresorhus"]) #over 700
print len(get_all_commits({"name":'CNTK', "user":'Microsoft'})) #check on github for actual number; as of 9/22/16 7899
ai_pulls = get_pulls({"name":"ToolBox-AI", "user":"sd16fall"})
print len(ai_pulls) #4
# print ai_pulls[0]
pass
|
IanOlin/github-research
|
Scraping/repo_info.py
|
Python
|
mit
| 6,716
|
#!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
Required,
)
app = Flask(__name__)
JqueryUiBootstrap(app)
app.config['SECRET_KEY'] = 'devkey'
app.config['RECAPTCHA_PUBLIC_KEY'] = '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw'
class ExampleForm(Form):
field1 = TextField('First Field', description='This is field one.')
field2 = TextField('Second Field', description='This is field two.',
validators=[Required()])
hidden_field = HiddenField('You cannot see this', description='Nope')
recaptcha = RecaptchaField('A sample recaptcha field')
def validate_hidden_field(form, field):
raise ValidationError('Always wrong')
@app.route('/', methods=('GET', 'POST',))
def index():
form = ExampleForm()
if form.validate_on_submit():
return "PASSED"
return render_template('example.html', form=form)
if '__main__' == __name__:
app.run(debug=True)
|
lightningwolf/Flask-JqueryUiBootstrap
|
SAMPLE_PROJECT/wtf-app.py
|
Python
|
mit
| 1,192
|
"""
Edge/Node Weighted Watersheds
====================================
Compare edge weighted watersheds
and node weighted on a grid graph.
"""
####################################
# sphinx_gallery_thumbnail_number = 5
from __future__ import print_function
import nifty.graph
import skimage.data
import skimage.segmentation
import vigra
import matplotlib
import pylab
import numpy
# increase default figure size
a,b = pylab.rcParams['figure.figsize']
pylab.rcParams['figure.figsize'] = 2.0*a, 2.0*b
####################################
# load some image
img = skimage.data.astronaut().astype('float32')
shape = img.shape[0:2]
#plot the image
pylab.imshow(img/255)
pylab.show()
################################################
# get some edge indicator
taggedImg = vigra.taggedView(img,'xyc')
edgeStrength = vigra.filters.structureTensorEigenvalues(taggedImg, 1.5, 1.9)[:,:,0]
edgeStrength = edgeStrength.squeeze()
edgeStrength = numpy.array(edgeStrength)
pylab.imshow(edgeStrength)
pylab.show()
###################################################
# get seeds via local minima
seeds = vigra.analysis.localMinima(edgeStrength)
seeds = vigra.analysis.labelImageWithBackground(seeds)
# plot seeds
cmap = numpy.random.rand ( seeds.max()+1,3)
cmap[0,:] = 0
cmap = matplotlib.colors.ListedColormap ( cmap)
pylab.imshow(seeds, cmap=cmap)
pylab.show()
#########################################
# grid graph
gridGraph = nifty.graph.undirectedGridGraph(shape)
#########################################
# run node weighted watershed algorithm
oversegNodeWeighted = nifty.graph.nodeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(),
nodeWeights=edgeStrength.ravel())
oversegNodeWeighted = oversegNodeWeighted.reshape(shape)
#########################################
# run edge weighted watershed algorithm
gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='sum')
numpy.random.permutation(gridGraphEdgeStrength)
oversegEdgeWeightedA = nifty.graph.edgeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(),
edgeWeights=gridGraphEdgeStrength)
oversegEdgeWeightedA = oversegEdgeWeightedA.reshape(shape)
#########################################
# run edge weighted watershed algorithm
# on interpixel weights.
# To do so we need to resample the image
# and compute the edge indicator
# on the reampled image
interpixelShape = [2*s-1 for s in shape]
imgBig = vigra.sampling.resize(taggedImg, interpixelShape)
edgeStrength = vigra.filters.structureTensorEigenvalues(imgBig, 2*1.5, 2*1.9)[:,:,0]
edgeStrength = edgeStrength.squeeze()
edgeStrength = numpy.array(edgeStrength)
gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='interpixel')
oversegEdgeWeightedB = nifty.graph.edgeWeightedWatershedsSegmentation(
graph=gridGraph,
seeds=seeds.ravel(),
edgeWeights=gridGraphEdgeStrength)
oversegEdgeWeightedB = oversegEdgeWeightedB.reshape(shape)
#########################################
# plot results
f = pylab.figure()
f.add_subplot(2,2, 1)
b_img = skimage.segmentation.mark_boundaries(img/255,
oversegEdgeWeightedA.astype('uint32'), mode='inner', color=(0.1,0.1,0.2))
pylab.imshow(b_img)
pylab.title('Edge Weighted Watershed (sum weights)')
f.add_subplot(2,2, 2)
b_img = skimage.segmentation.mark_boundaries(img/255,
oversegEdgeWeightedB.astype('uint32'), mode='inner', color=(0.1,0.1,0.2))
pylab.imshow(b_img)
pylab.title('Edge Weighted Watershed (interpixel weights)')
f.add_subplot(2,2, 3)
b_img = skimage.segmentation.mark_boundaries(img/255,
oversegNodeWeighted.astype('uint32'), mode='inner', color=(0.1,0.1,0.2))
pylab.imshow(b_img)
pylab.title('Node Weighted Watershed')
pylab.show()
|
DerThorsten/nifty
|
src/python/examples/graph/plot_undirected_grid_graph_watersheds.py
|
Python
|
mit
| 3,725
|
"""Contributed 'recipes'"""
|
alisaifee/flask-limiter
|
flask_limiter/contrib/__init__.py
|
Python
|
mit
| 28
|
import re
from versions.software.utils import get_command_stdout, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return '7-Zip'
def installed_version():
"""Return the installed version of 7-Zip, or None if not installed."""
try:
version_string = get_command_stdout('7z')
return version_string.split()[1]
except FileNotFoundError:
pass
def latest_version():
"""Return the latest version of 7-Zip available for download."""
soup = get_soup('http://www.7-zip.org/')
if soup:
tag = soup.find('b', string=re.compile('^Download'))
if tag:
return tag.text.split()[2]
return 'Unknown'
|
mchung94/latest-versions
|
versions/software/sevenzip.py
|
Python
|
mit
| 718
|
#sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing the arrival times
import time
#imports the url variables from config.py in the same folder
from config import *
#for talking to arduino
#******this is actually the pyserial library
import serial
#variables to hold the lists
arrival_times_york_south = []
arrival_times_york_north = []
arrival_times_high_south = []
arrival_times_high_north = []
#variable to hold the string to send to arduino
light_list = []
#opens up the serial connection with arduino
ser = serial.Serial('/dev/ttyACM0', 9600)
#this is necessary because once it opens up the serial port arduino needs a second
time.sleep(2)
#function to scrape the MTA site and add the arrival times to arrival_times lists
def grabber(station_ID, station_URL):
try:
#grabs the feed
feed = gtfs_realtime_pb2.FeedMessage()
response = urllib.urlopen(station_URL)
feed.ParseFromString(response.read())
#turns the feed into a dictionary
useful_dict = protobuf_to_dict(feed)
#this is the list of sub elements in useful_dict. basically it makes useful_dict slightly more manageable
useful_list = []
#walks through each train entry to see if it is an active train
for i in range (len(useful_dict['entity'])):
#this seems to be necessary, I'm not sure why
if useful_dict['entity'][i]['id']:
#adds the arrival information to useful_list
try:
useful_list.append(useful_dict['entity'][i]['trip_update']['stop_time_update'])
#if it is an entry that it not an active train, ignores
except KeyError:
pass
#pulls the entries tied to specific stops
small_list_station = [ i for i in chain.from_iterable(useful_list) if i['stop_id'] == station_ID ]
#list of arrival times to be filled by extracting info from small_list
arrival_times_station = []
#extracts the times from the small_list and adds to arrival_times list
for i in small_list_station:
#this is the arrival time of each train
the_time = i['arrival']['time']
#the_time - time.time gives you the seconds between arrival time and current time
arrival_time_in_minutes = (int(the_time) - int(time.time()))/60
#add arrival time to arrival_times list
arrival_times_station.append(arrival_time_in_minutes)
return arrival_times_station
#if there is an error getting an MTA feed it still returns something
#instead of borking the entire process
except:
print "Some sort of error getting the %s data" % station_ID
arrival_times_station = []
return arrival_times_station
#functionto convert arrival_times lists to a string to send to arduino
def lighter(arrival_list, light_one, light_two, light_three, light_four):
#walk through the numbers in the list
for item in arrival_list:
#convert the number to a number and see if it is in this
if 1 <= int(item) <= 8:
#if it is, add it to the list to send to the arduino
light_list.append(light_one)
elif 8 < int(item) <= 12:
light_list.append(light_two)
elif 12 < int(item) <=17:
light_list.append(light_three)
elif 17 < int(item) <=25:
light_list.append(light_four)
else:
pass
#clearn out arrival_times list for the next time around
#only relevant when this becomes a loop
arrival_list = []
#send the lights to arduino
def light_send():
#ser.write(light_string)
#figure out the current date and time
d = datetime.datetime.now()
#during the week
if d.weekday() in range(0, 6):
#is it between 7am and 9pm
#DONT USE () FOR HOURS
if d.hour in range(8, 22):
ser.write(light_string)
print "lights would be on weekday"
print light_string
else:
ser.write(off_string)
print "lights would be off"
print off_string
#on the weekend
elif d.weekday() in range(5, 7):
#between 8am and 10pm
if d.hour in range (9, 22):
ser.write(light_string);
print "lights would be on weekend"
print light_string
else:
ser.write(off_string)
print "lights would be off"
print off_string
else:
print "date error"
while True:
arrival_times_york_south = grabber('F18S', URL_F)
arrival_times_york_north = grabber('F18N', URL_F)
arrival_times_high_south = grabber('A40S', URL_AC)
arrival_times_high_north = grabber('A40N', URL_AC)
#debugging
print arrival_times_york_south
print arrival_times_york_north
print arrival_times_high_south
print arrival_times_high_north
lighter(arrival_times_york_south, 'a', 'b', 'c', 'd')
lighter(arrival_times_york_north, 'e', 'f', 'g', 'h')
lighter(arrival_times_high_south, 'i', 'j', 'k', 'l')
lighter(arrival_times_high_north, 'm', 'n', 'o', 'p')
#this adds the termination character that the arduino will be looking for
light_list.append('Z')
#this turns the list into a string to send to the arduino
light_string = ''.join(light_list)
#this is the off string for times when the light should be off
off_string = 'Y'
#debugging
print light_list
print light_string
#push string to arduino
light_send()
#empties light_list
light_list = []
print "sleeping for 20 seconds"
time.sleep(20)
|
mwweinberg/NYC-MTA-Next-Train
|
archive/nycmta.py
|
Python
|
mit
| 5,929
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nukebox2000 documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import nukebox2000
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'NukeBox2000'
copyright = u"2016, Darren Dowdall"
# 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 = nukebox2000.__version__
# The full version, including alpha/beta/rc tags.
release = nukebox2000.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# 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.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'nukebox2000doc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'nukebox2000.tex',
u'NukeBox2000 Documentation',
u'Darren Dowdall', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'nukebox2000',
u'NukeBox2000 Documentation',
[u'Darren Dowdall'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'nukebox2000',
u'NukeBox2000 Documentation',
u'Darren Dowdall',
'nukebox2000',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
|
k1nk33/NukeBox2000
|
docs/conf.py
|
Python
|
mit
| 8,447
|
import platform
import socket
import sys
import os
from mule_local.JobGeneration import *
from mule.JobPlatformResources import *
from . import JobPlatformAutodetect
# Underscore defines symbols to be private
_job_id = None
def get_platform_autodetect():
"""
Returns
-------
bool
True if current platform matches, otherwise False
"""
return JobPlatformAutodetect.autodetect()
def get_platform_id():
"""
Return platform ID
Returns
-------
string
unique ID of platform
"""
return "himmuc"
def get_platform_resources():
"""
Return information about hardware
"""
h = JobPlatformResources()
h.num_cores_per_node = 4
# Number of nodes per job are limited
h.num_nodes = 40
h.num_cores_per_socket = 4
h.max_wallclock_seconds = 8*60*60
return h
def jobscript_setup(jg : JobGeneration):
"""
Setup data to generate job script
"""
global _job_id
_job_id = jg.runtime.getUniqueID(jg.compile, jg.unique_id_filter)
return
def jobscript_get_header(jg : JobGeneration):
"""
These headers typically contain the information on e.g. Job exection, number of compute nodes, etc.
Returns
-------
string
multiline text for scripts
"""
global _job_id
p = jg.parallelization
time_str = p.get_max_wallclock_seconds_hh_mm_ss()
#
# See https://www.lrz.de/services/compute/linux-cluster/batch_parallel/example_jobs/
#
content = """#! /bin/bash
#SBATCH -o """+jg.p_job_stdout_filepath+"""
#SBATCH -e """+jg.p_job_stderr_filepath+"""
#SBATCH -D """+jg.p_job_dirpath+"""
#SBATCH -J """+_job_id+"""
#SBATCH --get-user-env
#SBATCH --nodes="""+str(p.num_nodes)+"""
#SBATCH --ntasks-per-node="""+str(p.num_ranks_per_node)+"""
# the above is a good match for the
# CooLMUC2 architecture.
#SBATCH --mail-type=end
#SBATCH --mail-user=schreiberx@gmail.com
#SBATCH --export=NONE
#SBATCH --time="""+time_str+"""
#SBATCH --partition=odr
"""
content += "\n"
content += "module load mpi\n"
if False:
if p.force_turbo_off:
content += """# Try to avoid slowing down CPUs
#SBATCH --cpu-freq=Performance
"""
content += """
source /etc/profile.d/modules.sh
"""
if jg.compile.threading != 'off':
content += """
export OMP_NUM_THREADS="""+str(p.num_threads_per_rank)+"""
"""
if p.core_oversubscription:
raise Exception("Not supported with this script!")
if p.core_affinity != None:
content += "\necho \"Affnity: "+str(p.core_affinity)+"\"\n"
if p.core_affinity == 'compact':
content += "\nexport OMP_PROC_BIND=close\n"
elif p.core_affinity == 'scatter':
content += "\nexport OMP_PROC_BIND=spread\n"
else:
raise Exception("Affinity '"+str(p.core_affinity)+"' not supported")
return content
def jobscript_get_exec_prefix(jg : JobGeneration):
"""
Prefix before executable
Returns
-------
string
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime)
return content
def jobscript_get_exec_command(jg : JobGeneration):
"""
Prefix to executable command
Returns
-------
string
multiline text for scripts
"""
p = jg.parallelization
mpiexec = ''
#
# Only use MPI exec if we are allowed to do so
# We shouldn't use mpiexec for validation scripts
#
if not p.mpiexec_disabled:
mpiexec = "mpiexec -n "+str(p.num_ranks)
content = """
# mpiexec ... would be here without a line break
EXEC=\""""+jg.compile.getProgramPath()+"""\"
PARAMS=\""""+jg.runtime.getRuntimeOptions()+"""\"
echo \"${EXEC} ${PARAMS}\"
"""+mpiexec+""" $EXEC $PARAMS || exit 1
"""
return content
def jobscript_get_exec_suffix(jg : JobGeneration):
"""
Suffix before executable
Returns
-------
string
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_suffix(jg.compile, jg.runtime)
return content
def jobscript_get_footer(jg : JobGeneration):
"""
Footer at very end of job script
Returns
-------
string
multiline text for scripts
"""
content = ""
return content
def jobscript_get_compile_command(jg : JobGeneration):
"""
Compile command(s)
This is separated here to put it either
* into the job script (handy for workstations)
or
* into a separate compile file (handy for clusters)
Returns
-------
string
multiline text with compile command to generate executable
"""
content = """
SCONS="scons """+jg.compile.getSConsParams()+' -j 4"'+"""
echo "$SCONS"
$SCONS || exit 1
"""
return content
|
schreiberx/sweet
|
mule/platforms/50_himmuc/JobPlatform.py
|
Python
|
mit
| 4,801
|
from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def curve(data, name="", smooth=True, trid=True):
"""
Creates a curve based on a list of (x,y) tuples.
Setting *smooth* to ``True`` results in a spline renderer renderer is used.
Setting *trid* to ``True`` results in a 3D plot. In this case the ``smooth``
argument is ignored.
"""
dataset = XYSeriesCollection()
xy = XYSeries(name);
for d in data:
xy.add(d[0], d[1])
dataset.addSeries(xy);
chart = ChartFactory.createXYLineChart(None, None, None, dataset,
PlotOrientation.VERTICAL, True, True, False)
if smooth:
chart.getXYPlot().setRenderer(XYSplineRenderer())
if trid:
chart.getXYPlot().setRenderer(XYLine3DRenderer())
return Chart(chart)
|
geoscript/geoscript-py
|
geoscript/plot/curve.py
|
Python
|
mit
| 991
|
# -*- coding: utf-8 -*-
"""
syslog2irc.main
~~~~~~~~~~~~~~~
:Copyright: 2007-2015 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from itertools import chain
from .announcer import create_announcer
from .processor import Processor
from .router import replace_channels_with_channel_names, Router
from .signals import irc_channel_joined, message_approved
from .syslog import start_syslog_message_receivers
from .util import log
# A note on threads (implementation detail):
#
# This tool uses threads. Besides the main thread, there are two
# additional threads: one for the syslog message receiver and one for
# the IRC bot. Both are configured to be daemon threads.
#
# A Python application exits if no more non-daemon threads are running.
#
# In order to exit syslog2IRC when shutdown is requested on IRC, the IRC
# bot will call `die()`, which will join the IRC bot thread. The main
# thread and the (daemonized) syslog message receiver thread remain.
#
# Additionally, a dedicated signal is sent that sets a flag that causes
# the main loop to stop. As the syslog message receiver thread is the
# only one left, but runs as a daemon, the application exits.
#
# The STDOUT announcer, on the other hand, does not run in a thread. The
# user has to manually interrupt the application to exit.
#
# For details, see the documentation on the `threading` module that is
# part of Python's standard library.
def start(irc_server, irc_nickname, irc_realname, routes, **options):
"""Start the IRC bot and the syslog listen server."""
try:
irc_channels = frozenset(chain(*routes.values()))
ports = routes.keys()
ports_to_channel_names = replace_channels_with_channel_names(routes)
announcer = create_announcer(irc_server, irc_nickname, irc_realname,
irc_channels, **options)
message_approved.connect(announcer.announce)
router = Router(ports_to_channel_names)
processor = Processor(router)
# Up to this point, no signals must have been sent.
processor.connect_to_signals()
# Signals are allowed be sent from here on.
start_syslog_message_receivers(ports)
announcer.start()
if not irc_server:
fake_channel_joins(router)
processor.run()
except KeyboardInterrupt:
log('<Ctrl-C> pressed, aborting.')
def fake_channel_joins(router):
for channel_name in router.get_channel_names():
irc_channel_joined.send(channel=channel_name)
|
Emantor/syslog2irc
|
syslog2irc/main.py
|
Python
|
mit
| 2,540
|
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import re
import poetryutils2
# this is all for use within ipython
def sample_words():
lines = poetryutils2.utils.debug_lines()
words = list()
for l in lines:
words.extend(w.lower() for w in l.split())
# maybe we want to clean words up more? let's just do that I think
# words = [w[:-1] for w in words if w[-1] in {'.',',','!','?'}]
# tofix = [w for w in words if w[-1] in {'.',',','!','?'}]
# words = [w for w in words if w[-1] not in {'.',',','!','?'}]
# words.extend([w[:-1] for w in tofix])
words = [re.sub(r'[^a-zA-Z\']', '', w) for w in words]
return [w for w in words if len(w)]
def realness(sample):
fails = [w for w in sample if not poetryutils2.utils.is_real_word(w)]
return fails
def main():
# print(len(sample_words()))
sample = sample_words()
print(len(sample))
fails = realness(sample)
# for f in fails:
# print(f)
from collections import Counter
counter = Counter(fails)
for word, count in counter.most_common():
if count > 1:
print(word, count)
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument('arg1', type=str, help="required argument")
# parser.add_argument('arg2', '--argument-2', help='optional boolean argument', action="store_true")
# args = parser.parse_args()
"""
okay so what we're having trouble with:
-est
-ies
-py
"""
if __name__ == "__main__":
main()
|
cmyr/poetryutils2
|
tests/realness_tests.py
|
Python
|
mit
| 1,555
|
from __future__ import unicode_literals
from collections import OrderedDict
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.text import slugify
from django.db import models
from decimal import Decimal
# Create your models here.
@python_2_unicode_compatible
class Installation(models.Model):
name = models.CharField(max_length=255, unique=True)
full_name = models.CharField(max_length=255)
is_active = models.BooleanField(default=False, help_text="Needs be active to show on dataverse.org map")
lat = models.DecimalField(max_digits=9, decimal_places=6, default=Decimal('0.0000'))
lng = models.DecimalField(max_digits=9, decimal_places=6, default=Decimal('0.0000'))
logo = models.ImageField(upload_to='logos/', null=True, blank=True)
marker = models.ImageField(upload_to='logos/', null=True, blank=True)
description = models.TextField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
slug = models.SlugField(max_length=255, blank=True, help_text='auto-filled on save')
version = models.CharField(max_length=6, blank=True, help_text='Dataversion version. e.g. "4.3", "3.6.2", etc')
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Installation, self).save(*args, **kwargs)
def view_logo_100(self):
#return self.logo.url
if self.logo:
return self.view_logo(force_width=100)
return 'n/a'
view_logo_100.allow_tags=True
def view_marker(self):
#return self.logo.url
if self.marker:
im = '<img src="%s" />' % (self.marker.url)
return im
return 'n/a'
view_marker.allow_tags=True
def view_logo(self, force_width=None):
#return self.logo.url
if self.logo:
if force_width:
im = ('<img src="{0}" width="{1}"/ >'
'<br />(width forced to {1}px)').format(\
self.logo.url, force_width)
return im
else:
im = '<img src="%s" />' % (self.logo.url)
return im
return 'n/a'
view_logo.allow_tags=True
def to_json(self, as_string=False, pretty=False):
"""Returns an OrderedDict of the installation attributes"""
od = OrderedDict()
od['id'] = self.id
od['name'] = self.name
od['full_name'] = self.full_name
od['is_active'] = self.is_active
od['description'] = self.description
od['lat'] = self.lat
od['lng'] = self.lng
od['logo'] = '%s://%s%s' % (settings.SWAGGER_SCHEME,
settings.SWAGGER_HOST,
self.logo.url)
#marker = self.marker
od['url'] = self.url
od['slug'] = self.slug
od['version'] = self.version if self.version else None
return od
@python_2_unicode_compatible
class Institution(models.Model):
name = models.CharField(max_length=255)
lat = models.DecimalField(max_digits=9, decimal_places=6, blank=False, default=Decimal('0.0000'))
lng = models.DecimalField(max_digits=9, decimal_places=6, blank=False, default=Decimal('0.0000'))
host = models.ForeignKey(
Installation,
on_delete=models.SET_NULL,
null=True,
blank=True
)
def __str__(self):
return self.name
|
IQSS/miniverse
|
dv_apps/installations/models.py
|
Python
|
mit
| 3,541
|
#
# Package analogous to 'threading.py' but using processes
#
# multiprocessing/__init__.py
#
# This package is intended to duplicate the functionality (and much of
# the API) of threading.py but uses processes instead of threads. A
# subpackage 'multiprocessing.dummy' has the same API but is a simple
# wrapper for 'threading'.
#
# Try calling `multiprocessing.doc.main()` to read the html
# documentation in a webbrowser.
#
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of author nor the names of any contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
__version__ = '0.70a1'
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array',
'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING',
]
__author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)'
#
# Imports
#
import os
import sys
from multiprocessing.process import Process, current_process, active_children
from multiprocessing.util import SUBDEBUG, SUBWARNING
#
# Exceptions
#
class ProcessError(Exception):
pass
class BufferTooShort(ProcessError):
pass
class TimeoutError(ProcessError):
pass
class AuthenticationError(ProcessError):
pass
# This is down here because _multiprocessing uses BufferTooShort
#import _multiprocessing
#
# Definitions not depending on native semaphores
#
def Manager():
'''
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m
def Pipe(duplex=True, buffer_id = None):
'''
Returns two connection object connected by a pipe
'''
from multiprocessing.connection import Pipe
return Pipe(duplex, buffer_id)
def cpu_count():
'''
Returns the number of CPUs in the system
'''
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif 'bsd' in sys.platform or sys.platform == 'darwin':
comm = '/sbin/sysctl -n hw.ncpu'
if sys.platform == 'darwin':
comm = '/usr' + comm
try:
with os.popen(comm) as p:
num = int(p.read())
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
num = 0
if num >= 1:
return num
else:
raise NotImplementedError('cannot determine number of cpus')
def freeze_support():
'''
Check whether this is a fake forked process in a frozen executable.
If so then run code specified by commandline and exit.
'''
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
from multiprocessing.forking import freeze_support
freeze_support()
def get_logger():
'''
Return package logger -- if it does not already exist then it is created
'''
from multiprocessing.util import get_logger
return get_logger()
def log_to_stderr(level=None):
'''
Turn on logging and add a handler which prints to stderr
'''
from multiprocessing.util import log_to_stderr
return log_to_stderr(level)
def allow_connection_pickling():
'''
Install support for sending connections and sockets between processes
'''
from multiprocessing import reduction
#
# Definitions depending on native semaphores
#
def Lock():
'''
Returns a non-recursive lock object
'''
from multiprocessing.synchronize import Lock
return Lock()
def RLock():
'''
Returns a recursive lock object
'''
from multiprocessing.synchronize import RLock
return RLock()
def Condition(lock=None):
'''
Returns a condition object
'''
from multiprocessing.synchronize import Condition
return Condition(lock)
def Semaphore(value=1):
'''
Returns a semaphore object
'''
from multiprocessing.synchronize import Semaphore
return Semaphore(value)
def BoundedSemaphore(value=1):
'''
Returns a bounded semaphore object
'''
from multiprocessing.synchronize import BoundedSemaphore
return BoundedSemaphore(value)
def Event():
'''
Returns an event object
'''
from multiprocessing.synchronize import Event
return Event()
def Queue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import Queue
return Queue(maxsize)
def JoinableQueue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
'''
Returns a process pool object
'''
from multiprocessing.pool import Pool
return Pool(processes, initializer, initargs, maxtasksperchild)
def RawValue(typecode_or_type, *args):
'''
Returns a shared object
'''
from multiprocessing.sharedctypes import RawValue
return RawValue(typecode_or_type, *args)
def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a shared array
'''
from multiprocessing.sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer)
def Value(typecode_or_type, *args, **kwds):
'''
Returns a synchronized shared object
'''
from multiprocessing.sharedctypes import Value
return Value(typecode_or_type, *args, **kwds)
def Array(typecode_or_type, size_or_initializer, **kwds):
'''
Returns a synchronized shared array
'''
from multiprocessing.sharedctypes import Array
return Array(typecode_or_type, size_or_initializer, **kwds)
#
#
#
if sys.platform == 'win32':
def set_executable(executable):
'''
Sets the path to a python.exe or pythonw.exe binary used to run
child processes on Windows instead of sys.executable.
Useful for people embedding Python.
'''
from multiprocessing.forking import set_executable
set_executable(executable)
__all__ += ['set_executable']
|
perkinslr/pypyjs
|
addedLibraries/multiprocessing/__init__.py
|
Python
|
mit
| 7,835
|
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/toolpath/VariantDir.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Verify that toolpath works with VariantDir() for an SConscript.
"""
import TestSCons
test = TestSCons.TestSCons()
test.subdir('subdir', ['subdir', 'src'], ['subdir', 'src', 'tools'])
test.write('SConstruct', """\
VariantDir('build', 'subdir', duplicate=0)
SConscript('build/SConscript')
""")
test.write(['subdir', 'SConscript'], """\
env = Environment(tools = ['MyBuilder'], toolpath = ['src/tools'])
env.MyCopy('src/file.out', 'src/file.in')
""")
test.write(['subdir', 'src', 'file.in'], "subdir/src/file.in\n")
test.write(['subdir', 'src', 'tools', 'MyBuilder.py'], """\
from SCons.Script import Builder
def generate(env):
def my_copy(target, source, env):
content = open(str(source[0]), 'rb').read()
open(str(target[0]), 'wb').write(content)
env['BUILDERS']['MyCopy'] = Builder(action = my_copy)
def exists(env):
return 1
""")
test.run()
test.must_match(['build', 'src', 'file.out'], "subdir/src/file.in\n")
# We should look for the underlying tool in both the build/src/tools
# (which doesn't exist) and subdir/src/tools (which still does). If we
# don't, the following would fail because the execution directory is
# now relative to the created VariantDir.
test.run()
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
EmanueleCannizzaro/scons
|
test/toolpath/VariantDir.py
|
Python
|
mit
| 2,582
|
# (c) 2015, Jon Hadfield <jon@lessknown.co.uk>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import *
from ansible.plugins.lookup import LookupBase
try:
import boto3
import botocore
except ImportError:
raise AnsibleError("aws_rds_endpoint_port_from_instance_name lookup cannot be run without boto installed")
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
region = terms[0][0]
instance_name = terms[0][1]
session=boto3.session.Session(region_name=region)
try:
rds_client=session.client('rds')
except botocore.exceptions.NoRegionError:
raise AnsibleError("AWS region not specified.")
result=rds_client.describe_db_instances(DBInstanceIdentifier=instance_name)
if result and result.get('DBInstances'):
return [result.get('DBInstances')[0].get('Endpoint').get('Port').encode('utf-8')]
return None
|
jonhadfield/ansible-lookups
|
aws_rds_endpoint_port_from_instance_name.py
|
Python
|
mit
| 1,218
|
from pylons_common.lib.log import create_logger
from pylons_common.lib.utils import pluralize
logger = create_logger('pylons_common.lib.datetime')
from datetime import datetime, timedelta
DATE_FORMAT_ACCEPT = [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%SZ', u'%Y-%m-%d', u'%m-%d-%Y', u'%m/%d/%Y', u'%m.%d.%Y', u'%b %d, %Y']
popular_timezones = [u'US/Eastern', u'US/Central', u'US/Mountain', u'US/Pacific', u'US/Alaska', u'US/Hawaii', u'US/Samoa',
u'Europe/London', u'Europe/Paris', u'Europe/Istanbul', u'Europe/Moscow',
u'America/Puerto_Rico', u'America/Buenos_Aires', u'America/Sao_Paulo',
u'Asia/Dubai', u'Asia/Calcutta', u'Asia/Rangoon', u'Asia/Bangkok', u'Asia/Hong_Kong', u'Asia/Tokyo',
u'Australia/Brisbane', u'Australia/Sydney',
u'Pacific/Fiji']
def convert_date(value):
"""
converts a string into a datetime object
"""
if not value:
return None
if isinstance(value, datetime):
return value
def try_parse(val, format):
try:
dt = datetime.strptime(val, format)
except ValueError:
dt = None
return dt
converted_value = None
for format in DATE_FORMAT_ACCEPT:
converted_value = converted_value or try_parse(value, format)
if not converted_value:
raise ValueError('Cannot convert supposed date %s' % value)
return converted_value
def get_timezones():
import pytz
timezones = {0:u'UTC'}
for tzname in pytz.common_timezones:
tzname = tzname.decode('utf-8')
tz = pytz.timezone(tzname)
dt = datetime.utcnow()
# in theory, this is more elegant, but tz.dst (timezone daylight savings - 0 if off 1 if on) is returning 0 for everything
#offset = tz.utcoffset(dt) - tz.dst(dt)
# we do this try/except to avoid the possibility that pytz fails at localization
# see https://bugs.launchpad.net/pytz/+bug/207500
try:
offset = dt.replace(tzinfo=pytz.utc) - tz.localize(dt)
seconds = offset.days * 86400 + offset.seconds
minutes = seconds / 60
hours = minutes / 60
# adjust for offsets that are greater than 12 hours (these are repeats of other offsets)
if hours > 12:
hours = hours - 24
elif hours < -11:
hours = hours + 24
this_tz = timezones.get(hours, None)
if not this_tz:
timezones[hours] = tzname
elif tzname in popular_timezones:
# overwrite timezones with popular ones if equivalent
timezones[hours] = tzname
except:
logger.exception("Localization failure for timezone " + tzname)
return timezones
def relative_date_str(date, now=None, time=False):
'''
Will return a string like 'Today', 'Tomorrow' etc.
'''
if not now: now = datetime.utcnow()
if not date: return 'unknown'
diff = date.date() - now.date()
def day_time(day_str):
return '%s%s' % (day_str, time and ' at %s' % date.strftime("%I:%M %p") or '')
if diff.days == 0:
return day_time('Today')
elif diff.days == -1:
return day_time('Yesterday')
elif diff.days == 1:
return day_time('Tomorrow')
elif diff.days < 0 and diff.days >= -7:#Within one week back
return '%s ago' % pluralize(-diff.days, '{0} days', '1 day')
elif diff.days > 0 and diff.days < 7:#Within one week back
return 'in %s' % pluralize(diff.days, '{0} days', '1 day')
else:
return date.strftime("%b %e, %Y")## on 10/03/1980
def now():
return datetime.utcnow()
|
benogle/pylons_common
|
pylons_common/lib/date.py
|
Python
|
mit
| 3,799
|
from etvnet_service import EtvnetService
from plex_config import PlexConfig
class PlexVideoService(EtvnetService):
def __init__(self):
config_name = Core.storage.abs_path(Core.storage.join_path(Core.bundle_path, 'Contents', 'etvnet.config'))
config = PlexConfig(config_name)
EtvnetService.__init__(self, config)
|
shvets/Etvnet.bundle
|
Contents/Code/plex_video_service.py
|
Python
|
mit
| 342
|
#!/usr/bin/env python2
from hgraph import Hgraph
import amr_graph_description_parser
#import tree
import re
import sys
import string
from collections import defaultdict as ddict
def format_tagged(s):
#return [tuple(p.split('/')) for p in s.split()]
return [p.rsplit('-',1)[0] for p in s.split()]
def format_amr(l):
amr_s = ' '.join(l)
amr_g = Hgraph.from_string(amr_s)
return amr_g
def read_to_empty(f):
lines = []
while True:
l = f.readline().strip()
if not l: return lines
lines.append(l)
def format_constituents(l):
return nltk.tree.ParentedTree("\n".join(l))
def format_alignments(l, amr):
"""
Parse alignment descriptions from file
"""
r = []
for a in l:
m = re.match(r'(\S+)\s+:(\S+)\s+(\S+)\s+(.+)\-(\d+)', a)
if m:
var = m.group(1)
role = m.group(2)
filler = m.group(3).replace('"','')
token = m.group(4)
token_id = int(m.group(5)) - 1
else:
m = re.match(r'ROOT\s+([^\-]+)\-(\d+)', a)
if m:
var = None
role = "ROOT"
filler = amr.roots[0].replace('"','')
token = m.group(1)
token_id = int(m.group(2)) - 1
else:
sys.exit(1)
amr_triple = (var, role, (filler,))
r.append((amr_triple, token_id))
return r
textlinematcher = re.compile("^(\d+)\.(.*?)\((.*)\)?$")
def format_text(l):
match = textlinematcher.match(l.strip())
if not match:
raise ValueError, "Not a valid text line in Ulf corpus: \n %s \n"%l
s_no = int(match.group(1))
text = match.group(2).strip().split(" ")
s_id = match.group(3).strip()
return s_id, s_no, text
def plain_corpus(f):
while True:
x = read_to_empty(f)
if not x:
raise StopIteration
amr = format_amr(x)
yield amr
def aligned_corpus(f):
"""
Read the next parsed sentence from an input file using the aligned AMR/tagged string format.
"""
while True:
l = f.readline()
if not l:
raise StopIteration
while l.strip().startswith("#") or l.strip().startswith("==") or not l.strip():
l = f.readline()
if not l:
raise IOError, "AMR data file ended unexpectedly."
sent_id = int(l)
l = f.readline()
amr = format_amr(read_to_empty(f))
tagged = format_tagged(f.readline())
l = f.readline()
alignments = format_alignments(read_to_empty(f), amr)
p = SentenceWithHgraph(sent_id, sent_id, amr, tagged, None, alignments)
yield p
def ulf_corpus(f):
"""
Read the next parsed sentence from an input file using Ulf's format.
"""
while True:
l = f.readline()
if not l:
raise StopIteration
while l.strip().startswith("#") or not l.strip():
l = f.readline()
if not l:
raise IOError, "AMR data file ended unexpectedly- sentence without AMR."
sent_id, sent_no, tagged = format_text(l.strip())
l = f.readline()
amr = format_amr(read_to_empty(f))
p = SentenceWithHgraph(sent_id, sent_no, amr, tagged, None, None)
yield p
def metadata_amr_corpus(f):
"""
Read the next parsed sentence from an input file using the AMR meta data format.
"""
metadata = []
sentence = ""
sent_id = ""
buff = []
idmatcher = re.compile("# ::id ([^ ]+) ")
sentmatcher = re.compile("# ::snt (.*)")
count = 1
parser = amr_graph_description_parser.GraphDescriptionParser()
while True:
l = f.readline()
if not l:
raise StopIteration
l = l.strip()
if not l:
if buff:
amr = parser.parse_string(" ".join(buff))
yield SentenceWithHgraph(sent_id, count, amr, sentence, metadata = metadata)
count += 1
buff = []
metadata = []
sentence = ""
sent_id = ""
elif l.startswith("#"):
metadata.append(l)
match = idmatcher.match(l)
if match:
sent_id = match.group(1)
match = sentmatcher.match(l)
if match:
sentence = match.group(1)
else:
buff.append(l)
class SentenceWithHgraph():
"""
A data structure to hold Hgraph <-> sentence pairs with
PTB parses and token to Hgraph edge elignments.
"""
def __init__(self, sent_id, sent_no, amr, tagged, ptb = None, edge_alignments = None, metadata = None):
self.sent_no = sent_no
self.sent_id = sent_id
self.amr = amr
self.tagged = tagged
self.ptb = ptb
self.alignments = edge_alignments
self.metadata = metadata
#in_f = open(sys.argv[1],'r')
#corpus = metadata_amr_corpus(in_f)
|
isi-nlp/bolinas
|
common/hgraph/amr_corpus_reader.py
|
Python
|
mit
| 4,973
|
import hypertrack
hypertrack.secret_key = 'c237rtyfeo9893u2t4ghoevslsd'
customer = hypertrack.Customer.create(
name='John Doe',
email='john@customer.com',
phone='+15555555555',
)
print(customer)
|
hypertrack/hypertrack-python
|
example.py
|
Python
|
mit
| 211
|
from datetime import date, datetime, timedelta
from itertools import chain
from operator import attrgetter
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.db.models import Q, get_app
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.translation import ugettext
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from pinax.utils.importlib import import_module
# Only import dpaste Snippet Model if it's activated
if "dpaste" in getattr(settings, "INSTALLED_APPS"):
from dpaste.models import Snippet
else:
Snippet = False
if "notification" in getattr(settings, "INSTALLED_APPS"):
from notification import models as notification
else:
notification = None
from tagging.models import Tag
from .models import Milestone
from .filters import MilestoneFilter
from .forms import MilestoneForm, EditMilestoneForm
def milestones(request, group_slug=None, template_name="milestones/milestone_list.html", bridge=None):
if bridge:
try:
group = bridge.get_group(group_slug)
except ObjectDoesNotExist:
raise Http404
else:
group = None
if not request.user.is_authenticated():
is_member = False
else:
if group:
is_member = group.user_is_member(request.user)
else:
is_member = True
group_by = request.GET.get("group_by")
if group:
milestones = group.content_objects(Milestone)
group_base = bridge.group_base_template()
else:
milestones = Milestone.objects.filter(object_id=None)
group_base = None
# default filtering
state_keys = dict(Milestone.STATE_CHOICES).keys()
default_states = set(state_keys).difference(
# don"t show these states
set(["2"])
)
filter_data = {"state": list(default_states)}
filter_data.update(request.GET)
milestone_filter = MilestoneFilter(filter_data, queryset=milestones)
group_by_querydict = request.GET.copy()
group_by_querydict.pop("group_by", None)
group_by_querystring = group_by_querydict.urlencode()
return render_to_response(template_name, {
"group": group,
"group_by": group_by,
"gbqs": group_by_querystring,
"is_member": is_member,
"group_base": group_base,
"milestone_filter": milestone_filter,
"milestones": milestone_filter.qs,
"querystring": request.GET.urlencode(),
}, context_instance=RequestContext(request))
def add_milestone(request, group_slug=None, secret_id=None,
form_class=MilestoneForm,
template_name="milestones/add.html", bridge=None):
if bridge:
try:
group = bridge.get_group(group_slug)
except ObjectDoesNotExist:
raise Http404
else:
group = None
if group:
group_base = bridge.group_base_template()
else:
group_base = None
if not request.user.is_authenticated():
is_member = False
else:
if group:
is_member = group.user_is_member(request.user)
else:
is_member = True
initial = {}
if request.method == "POST":
if request.user.is_authenticated():
milestone_form = form_class(request.user, group, request.POST)
if milestone_form.is_valid():
milestone = milestone_form.save(commit=False)
milestone.creator = request.user
milestone.group = group
#if hasattr(workflow, "initial_state"):
# milestone.state = workflow.initial_state(milestone, user)
milestone.save()
#milestone.save_history()
messages.add_message(request, messages.SUCCESS,
ugettext("added milestone '%s'") % milestone.title
)
if notification:
if group:
notify_list = group.member_queryset()
else:
notify_list = User.objects.all() # @@@
notify_list = notify_list.exclude(id__exact=request.user.id)
notification.send(notify_list, "milestones_new",
{"creator": request.user,
"milestone": milestone, "group": group})
if request.POST.has_key("add-another-milestone"):
if group:
redirect_to = bridge.reverse("milestone_add", group)
else:
redirect_to = reverse("milestone_add")
return HttpResponseRedirect(redirect_to)
if group:
redirect_to = bridge.reverse("milestone_list", group)
else:
redirect_to = reverse("milestone_list")
return HttpResponseRedirect(redirect_to)
else:
milestone_form = form_class(request.user, group, initial=initial)
return render_to_response(template_name, {
"group": group,
"is_member": is_member,
"milestone_form": milestone_form,
"group_base": group_base,
}, context_instance=RequestContext(request))
def milestone_detail(request, id, group_slug=None,
template_name="milestones/milestone.html", bridge=None):
if bridge:
try:
group = bridge.get_group(group_slug)
except ObjectDoesNotExist:
raise Http404
else:
group = None
if group:
milestones = group.content_objects(Milestone)
group_base = bridge.group_base_template()
else:
milestones = Milestone.objects.filter(object_id=None)
group_base = None
milestone = get_object_or_404(milestones, id=id)
if group:
notify_list = group.member_queryset()
else:
notify_list = User.objects.all()
notify_list = notify_list.exclude(id__exact=request.user.id)
if not request.user.is_authenticated():
is_member = False
else:
if group:
is_member = group.user_is_member(request.user)
else:
is_member = True
## milestone tasks
from tasks.models import Task
from tasks import workflow
from tasks.filters import TaskFilter
group_by = request.GET.get("group_by")
if group:
tasks = group.content_objects(Task)
group_base = bridge.group_base_template()
else:
tasks = Task.objects.filter(object_id=None)
group_base = None
tasks = tasks.select_related("assignee")
# default filtering
state_keys = dict(workflow.STATE_CHOICES).keys()
default_states = set(state_keys)
filter_data = {"state": list(default_states)}
filter_data.update(request.GET)
task_filter = TaskFilter(filter_data, queryset=tasks)
group_by_querydict = request.GET.copy()
group_by_querydict.pop("group_by", None)
group_by_querystring = group_by_querydict.urlencode()
return render_to_response(template_name, {
"group": group,
"milestone": milestone,
"is_member": is_member,
"group_base": group_base,
"group_by": group_by,
"gbqs": group_by_querystring,
"is_member": is_member,
"task_filter": task_filter,
"tasks": task_filter.qs.filter(milestone=milestone),
"querystring": request.GET.urlencode(),
}, context_instance=RequestContext(request))
@login_required
def milestone_edit(request, id, group_slug=None,
template_name="milestones/edit.html", bridge=None):
if bridge:
try:
group = bridge.get_group(group_slug)
except ObjectDoesNotExist:
raise Http404
else:
group = None
if group:
milestones = group.content_objects(Milestone)
group_base = bridge.group_base_template()
else:
milestones = Milestone.objects.filter(object_id=None)
group_base = None
milestone = get_object_or_404(milestones, id=id)
if group:
notify_list = group.member_queryset()
else:
notify_list = User.objects.all()
notify_list = notify_list.exclude(id__exact=request.user.id)
if group:
is_member = group.user_is_member(request.user)
else:
is_member = True
if not is_member:
messages.add_message(request, messages.ERROR,
ugettext("You can't edit milestones unless you are a project member")
)
return HttpResponseRedirect(reverse("project_list"))
if is_member and request.method == "POST":
form = EditMilestoneForm(request.user, group, request.POST, instance=milestone)
if form.is_valid():
milestone = form.save()
if "state" in form.changed_data:
messages.add_message(request, messages.SUCCESS,
ugettext("milestone marked %(state)s") % {
"state": milestone.get_state_display()
}
)
if notification:
notification.send(notify_list, "milestones_change", {"user": request.user, "milestone": milestone, "group": group, "new_state": milestone.get_state_display()})
form = EditMilestoneForm(request.user, group, instance=milestone)
else:
form = EditMilestoneForm(request.user, group, instance=milestone)
return render_to_response(template_name, {
"group": group,
"milestone": milestone,
"is_member": is_member,
"form": form,
"group_base": group_base
}, context_instance=RequestContext(request))
|
hbussell/pinax-tracker
|
apps/milestones/views.py
|
Python
|
mit
| 10,170
|
"""
__MT_post__Par.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: gehan
Modified: Sun Feb 15 10:31:27 2015
______________________________________________________________________
"""
from ASGNode import *
from ATOM3Type import *
from ATOM3Text import *
from ATOM3String import *
from graph_MT_post__Par import *
class MT_post__Par(ASGNode, ATOM3Type):
def __init__(self, parent = None):
ASGNode.__init__(self)
ATOM3Type.__init__(self)
self.superTypes = ['MT_post__Proc', 'MT_post__MetaModelElement_T']
self.graphClass_ = graph_MT_post__Par
self.isGraphObjectVisual = True
if(hasattr(self, '_setHierarchicalLink')):
self._setHierarchicalLink(False)
if(hasattr(self, '_setHierarchicalNode')):
self._setHierarchicalNode(False)
self.parent = parent
self.MT_post__cardinality=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_post__cardinality=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_post__classtype=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_post__classtype=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_post__name=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_post__name=ATOM3Text('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n', 80,15 )
self.MT_label__=ATOM3String('', 20)
self.MT_pivotOut__=ATOM3String('', 20)
self.generatedAttributes = {'MT_post__cardinality': ('ATOM3Text', ),
'MT_post__cardinality': ('ATOM3Text', ),
'MT_post__classtype': ('ATOM3Text', ),
'MT_post__classtype': ('ATOM3Text', ),
'MT_post__name': ('ATOM3Text', ),
'MT_post__name': ('ATOM3Text', ),
'MT_label__': ('ATOM3String', ),
'MT_pivotOut__': ('ATOM3String', ) }
self.realOrder = ['MT_post__cardinality','MT_post__cardinality','MT_post__classtype','MT_post__classtype','MT_post__name','MT_post__name','MT_label__','MT_pivotOut__']
self.directEditing = [0,0,0,0,0,0,1,1]
def clone(self):
cloneObject = MT_post__Par( self.parent )
for atr in self.realOrder:
cloneObject.setAttrValue(atr, self.getAttrValue(atr).clone() )
ASGNode.cloneActions(self, cloneObject)
return cloneObject
def copy(self, other):
ATOM3Type.copy(self, other)
for atr in self.realOrder:
self.setAttrValue(atr, other.getAttrValue(atr) )
ASGNode.copy(self, other)
def preCondition (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.preCondition(actionID, params)
else: return None
def postCondition (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.postCondition(actionID, params)
else: return None
def preAction (self, actionID, * params):
if actionID == self.CREATE:
self.autoIncrLabel(params)
if self.graphObject_:
return self.graphObject_.preAction(actionID, params)
else: return None
def postAction (self, actionID, * params):
if self.graphObject_:
return self.graphObject_.postAction(actionID, params)
else: return None
def QOCA(self, params):
"""
QOCA Constraint Template
NOTE: DO NOT select a POST/PRE action trigger
Constraints will be added/removed in a logical manner by other mechanisms.
"""
return # <---- Remove this to use QOCA
""" Get the high level constraint helper and solver """
from Qoca.atom3constraints.OffsetConstraints import OffsetConstraints
oc = OffsetConstraints(self.parent.qocaSolver)
"""
Example constraint, see Kernel/QOCA/atom3constraints/OffsetConstraints.py
For more types of constraints
"""
oc.fixedWidth(self.graphObject_, self.graphObject_.sizeX)
oc.fixedHeight(self.graphObject_, self.graphObject_.sizeY)
def autoIncrLabel(self, params):
#===============================================================================
# Auto increment the label
#===============================================================================
# If there is already one, ignore
if not self.MT_label__.isNone(): return
# Get the maximum label of all MT_pre__ elements
label = 0
for nt in self.parent.ASGroot.listNodes:
if nt.startswith('MT_post__'):
for node in self.parent.ASGroot.listNodes[nt]:
currLabel = 0
try:
currLabel = int(node.MT_label__.getValue())
except:
pass
if currLabel > label:
label = currLabel
# The label of this instance will be the max label + 1
self.MT_label__.setValue(str(label + 1))
|
levilucio/SyVOLT
|
UMLRT2Kiltera_MM/MT_post__Par.py
|
Python
|
mit
| 9,121
|
"""DICOM Upper Layer Protocol Data Units (PDUs).
There are seven different PDUs:
- A_ASSOCIATE_RQ
- A_ASSOCIATE_AC
- A_ASSOCIATE_RJ
- P_DATA_TF
- A_RELEASE_RQ
- A_RELEASE_RP
- A_ABORT_RQ
::
from_primitive encode
+----------------+ ------> +------------+ -----> +-------------+
| DUL Primitive | | PDU | | Peer AE |
+----------------+ <------ +------------+ <----- +-------------+
to_primitive decode
"""
import codecs
import logging
from struct import Struct
from pynetdicom.pdu_items import (
ApplicationContextItem,
PresentationContextItemRQ,
PresentationContextItemAC,
UserInformationItem,
PresentationDataValueItem,
PDU_ITEM_TYPES
)
from pynetdicom.utils import validate_ae_title
LOGGER = logging.getLogger('pynetdicom.pdu')
# Predefine some structs to make decoding and encoding faster
UCHAR = Struct('B')
UINT2 = Struct('>H')
UINT4 = Struct('>I')
UNPACK_UCHAR = UCHAR.unpack
UNPACK_UINT2 = UINT2.unpack
UNPACK_UINT4 = UINT4.unpack
PACK_UCHAR = UCHAR.pack
PACK_UINT2 = UINT2.pack
PACK_UINT4 = UINT4.pack
class PDU(object):
"""Base class for PDUs.
Protocol Data Units (PDUs) are the message formats exchanged between peer
entities within a layer. A PDU consists of protocol control information
and user data. PDUs are constructed by mandatory fixed fields followed by
optional variable fields that contain one or more items and/or sub-items.
References
----------
DICOM Standard, Part 8, :dcm:`Section 9.3 <part08/sect_9.3.html>`
"""
def decode(self, bytestream):
"""Decode `bytestream` and use the result to set the field values of
the PDU.
Parameters
----------
bytestream : bytes
The PDU data to be decoded.
"""
for (offset, length), attr_name, func, args in self._decoders:
# Allow us to use None as a `length`
if length:
sl = slice(offset, offset + length)
else:
sl = slice(offset, None)
setattr(
self, attr_name, func(bytestream[sl], *args)
)
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders."""
raise NotImplementedError
def encode(self):
"""Return the encoded PDU as :class:`bytes`.
Returns
-------
bytes
The encoded PDU.
"""
bytestream = bytes()
for attr_name, func, args in self._encoders:
# If attr_name is None then the field is usually reserved
if attr_name:
bytestream += func(getattr(self, attr_name), *args)
else:
bytestream += func(*args)
return bytestream
@property
def _encoders(self):
"""Return an iterable of tuples that contain field encoders."""
raise NotImplementedError
def __eq__(self, other):
"""Return ``True`` if `self` equals `other`."""
if other is self:
return True
# pylint: disable=protected-access
if isinstance(other, self.__class__):
self_dict = {
enc[0] : getattr(self, enc[0])
for enc in self._encoders if enc[0]
}
other_dict = {
enc[0] : getattr(other, enc[0])
for enc in other._encoders if enc[0]
}
return self_dict == other_dict
return NotImplemented
@staticmethod
def _generate_items(bytestream):
"""Yield PDU item data from `bytestream`.
Parameters
----------
bytestream : bytes
The encoded PDU variable item data.
Yields
------
int, bytes
The variable item's 'Item Type' parameter as int, and the item's
entire encoded data as bytes.
Notes
-----
Can be used with the following PDU items/sub-items:
- Application Context Item
- Presentation Context Item (RQ/AC)
- Abstract Syntax Sub-item
- Transfer Syntax Sub-item
- User Information Item
- Implementation Class UID Sub-item (RQ/AC)
- Implementation Version Name Sub-item (RQ/AC)
- Asynchronous Operations Window Sub-item (RQ/AC)
- SCP/SCU Role Selection Sub-item (RQ/AC)
- SOP Class Extended Negotiation Sub-item (RQ/AC)
- SOP Class Common Extended Negotiation Sub-item (RQ/AC)
- User Identity Sub-item (RQ/AC)
**Encoding**
When encoded, PDU item and sub-item data for the above has the
following structure, taken from various tables in (offsets shown
with Python indexing). Items are always encoded using Big Endian.
+--------+-------------+-------------+
| Offset | Length | Description |
+========+=============+=============+
| 0 | 1 | Item type |
+--------+-------------+-------------+
| 1 | 1 | Reserved |
+--------+-------------+-------------+
| 2 | 2 | Item length |
+--------+-------------+-------------+
| 4 | Item length | Item data |
+--------+-------------+-------------+
References
----------
* DICOM Standard, Part 8, :dcm:`Section 9.3 <part08/sect_9.3.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
offset = 0
while bytestream[offset:offset + 1]:
item_type = UNPACK_UCHAR(bytestream[offset:offset + 1])[0]
item_length = UNPACK_UINT2(bytestream[offset + 2:offset + 4])[0]
item_data = bytestream[offset:offset + 4 + item_length]
assert len(item_data) == 4 + item_length
yield item_type, item_data
# Move `offset` to the start of the next item
offset += 4 + item_length
def __len__(self):
"""Return the total length of the encoded PDU as :class:`int`."""
return 6 + self.pdu_length
def __ne__(self, other):
"""Return ``True`` if `self` does not equal `other`."""
return not self == other
@property
def pdu_length(self):
"""Return the *PDU Length* field value as :class:`int`."""
raise NotImplementedError
@property
def pdu_type(self):
"""Return the *PDU Type* field value as :class:`int`."""
return PDU_TYPES[self.__class__]
@staticmethod
def _wrap_bytes(bytestream):
"""Return `bytestream` without changing it."""
return bytestream
@staticmethod
def _wrap_encode_items(items):
"""Return `items` encoded as bytes.
Parameters
----------
items : list of PDU items
The items to encode.
Returns
-------
bytes
The encoded items.
"""
bytestream = bytes()
for item in items:
bytestream += item.encode()
return bytestream
@staticmethod
def _wrap_encode_uid(uid):
"""Return `uid` as bytes encoded using ASCII.
Each component of Application Context, Abstract Syntax and Transfer
Syntax UIDs should be encoded as a ISO 646:1990-Basic G0 Set Numeric
String (characters 0-9), with each component separated by '.' (0x2e)
.
'ascii' is chosen because this is the codec Python uses for ISO 646
[3]_.
Parameters
----------
uid : pydicom.uid.UID
The UID to encode using ASCII.
Returns
-------
bytes
The encoded `uid`.
References
----------
* DICOM Standard, Part 8, :dcm:`Annex F <part08/chapter_F.html>`
* `Python 3 codecs module
<https://docs.python.org/2/library/codecs.html#standard-encodings>`_
"""
return codecs.encode(uid, 'ascii')
def _wrap_generate_items(self, bytestream):
"""Return a list of encoded PDU items generated from `bytestream`."""
item_list = []
for item_type, item_bytes in self._generate_items(bytestream):
item = PDU_ITEM_TYPES[item_type]()
item.decode(item_bytes)
item_list.append(item)
return item_list
@staticmethod
def _wrap_pack(value, packer):
"""Return `value` encoded as bytes using `packer`.
Parameters
----------
value
The value to encode.
packer : callable
A callable function to use to pack the data as bytes. The
`packer` should return the packed bytes. Example:
struct.Struct('>I').pack
Returns
-------
bytes
"""
return packer(value)
@staticmethod
def _wrap_unpack(bytestream, unpacker):
"""Return the first value when `unpacker` is run on `bytestream`.
Parameters
----------
bytestream : bytes
The encoded data to unpack.
unpacker : callable
A callable function to use to unpack the data in `bytestream`. The
`unpacker` should return a tuple containing unpacked values.
Example: struct.Struct('>I').unpack.
"""
return unpacker(bytestream)[0]
class A_ASSOCIATE_RQ(PDU):
"""An A-ASSOCIATE-RQ PDU.
An A-ASSOCIATE-RQ PDU is sent by an association requestor to initiate
association negotiation with an acceptor.
Attributes
----------
application_context_name : pydicom.uid.UID or None
The Application Context Item's *Application Context Name* field value
(if available).
called_ae_title : bytes
The *Called AE Title* field value, which is the destination DICOM
application name as a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
calling_ae_title : bytes
The *Calling AE Title* field value, which is the destination DICOM
application name as a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x01``).
presentation_context : list of pdu_items.PresentationContextItemRQ
The *Presentation Context Item(s)*.
protocol_version : int
The *Protocol Version* field value (``0x01``).
user_information : pdu_items.UserInformationItem
The *User Information Item* (if available).
variable_items : list
A list containing the A-ASSOCIATE-RQ's *Variable Items*. Contains
one Application Context item, one or more Presentation Context items
and one User Information item. The order of the items is not
guaranteed.
Notes
-----
An A-ASSOCIATE-RQ PDU requires the following parameters:
* PDU type (1, fixed value, ``0x01``)
* PDU length (1)
* Protocol version (1, default value, ``0x01``)
* Called AE title (1)
* Calling AE title (1)
* Variable items (1)
* Application Context Item (1)
* Item type (1, fixed value, ``0x10``)
* Item length (1)
* Application Context Name (1, fixed in an application)
* Presentation Context Item(s) (1 or more)
* Item type (1, fixed value, ``0x21``)
* Item length (1)
* Context ID (1)
* Abstract/Transfer Syntax Sub-items (1)
* Abstract Syntax Sub-item (1)
* Item type (1, fixed, ``0x30``)
* Item length (1)
* Abstract syntax name (1)
* Transfer Syntax Sub-items (1 or more)
* Item type (1, fixed, ``0x40``)
* Item length (1)
* Transfer syntax name(s) (1 or more)
* User Information Item (1)
* Item type (1, fixed, ``0x50``)
* Item length (1)
* User data Sub-items (2 or more)
* Maximum Length Received Sub-item (1)
* Implementation Class UID Sub-item (1)
* Optional User Data Sub-items (0 or more)
**Encoding**
When encoded, an A-ASSOCIATE-RQ PDU has the following structure, taken
from `Table 9-11<part08/sect_9.3.2.html>` (offsets shown with Python
indexing). PDUs are always encoded using Big Endian.
+--------+-------------+------------------+
| Offset | Length | Description |
+========+=============+==================+
| 0 | 1 | PDU type |
+--------+-------------+------------------+
| 1 | 1 | Reserved |
+--------+-------------+------------------+
| 2 | 4 | PDU length |
+--------+-------------+------------------+
| 6 | 2 | Protocol version |
+--------+-------------+------------------+
| 8 | 2 | Reserved |
+--------+-------------+------------------+
| 10 | 16 | Called AE title |
+--------+-------------+------------------+
| 26 | 16 | Calling AE title |
+--------+-------------+------------------+
| 42 | 32 | Reserved |
+--------+-------------+------------------+
| 74 | Variable | Variable items |
+--------+-------------+------------------+
References
----------
* DICOM Standard, Part 8, Sections :dcm:`9.3.2<part08/sect_9.3.2.html>`
and :dcm:`9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-ASSOCIATE-RQ PDU."""
# We allow the user to modify the protocol version if so desired
self.protocol_version = 0x01
# Set some default values
self.called_ae_title = "Default"
self.calling_ae_title = "Default"
# `variable_items` is a list containing the following:
# 1 ApplicationContextItem
# 1 or more PresentationContextItemRQ
# 1 UserInformationItem
# The order of the items in the list may not be as given above
self.variable_items = []
def from_primitive(self, primitive):
"""Setup the current PDU using an A-ASSOCIATE (request) primitive.
Parameters
----------
primitive : pdu_primitives.A_ASSOCIATE
The primitive to use to set the current PDU field values.
"""
self.calling_ae_title = primitive.calling_ae_title
self.called_ae_title = primitive.called_ae_title
# Add Application Context
application_context = ApplicationContextItem()
application_context.application_context_name = (
primitive.application_context_name
)
self.variable_items.append(application_context)
# Add Presentation Context(s)
for contexts in primitive.presentation_context_definition_list:
presentation_context = PresentationContextItemRQ()
presentation_context.from_primitive(contexts)
self.variable_items.append(presentation_context)
# Add User Information
user_information = UserInformationItem()
user_information.from_primitive(primitive.user_information)
self.variable_items.append(user_information)
def to_primitive(self):
"""Return an A-ASSOCIATE (request) primitive from the current PDU.
Returns
-------
pdu_primitives.A_ASSOCIATE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ASSOCIATE
primitive = A_ASSOCIATE()
primitive.calling_ae_title = self.calling_ae_title
primitive.called_ae_title = self.called_ae_title
primitive.application_context_name = self.application_context_name
for item in self.variable_items:
# Add presentation contexts
if isinstance(item, PresentationContextItemRQ):
primitive.presentation_context_definition_list.append(
item.to_primitive())
# Add user information
elif isinstance(item, UserInformationItem):
primitive.user_information = item.to_primitive()
return primitive
@property
def application_context_name(self):
"""Return the *Application Context Name*, if available.
Returns
-------
pydicom.uid.UID or None
The requestor's *Application Context Name* or None if not
available.
"""
for item in self.variable_items:
if isinstance(item, ApplicationContextItem):
return item.application_context_name
return None
@property
def called_ae_title(self):
"""Return the *Called AE Title* field value as :class:`bytes`."""
return self._called_aet
@called_ae_title.setter
def called_ae_title(self, ae_title):
"""Set the *Called AE Title* field value.
Will be converted to a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
Parameters
----------
ae_title : str or bytes
The value you wish to set. A value consisting of spaces is not
allowed and values longer than 16 characters will be truncated.
"""
# pylint: disable=attribute-defined-outside-init
if isinstance(ae_title, str):
ae_title = codecs.encode(ae_title, 'ascii')
self._called_aet = validate_ae_title(ae_title)
@property
def calling_ae_title(self):
"""Return the *Calling AE Title* field value as :class:`bytes`."""
return self._calling_aet
@calling_ae_title.setter
def calling_ae_title(self, ae_title):
"""Set the *Calling AE Title* field value.
Will be converted to a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
Parameters
----------
ae_title : str or bytes
The value you wish to set. A value consisting of spaces is not
allowed and values longer than 16 characters will be truncated.
"""
# pylint: disable=attribute-defined-outside-init
if isinstance(ae_title, str):
ae_title = codecs.encode(ae_title, 'ascii')
self._calling_aet = validate_ae_title(ae_title)
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ``((offset, length), attr_name, callable, [args])``,
where:
- ``offset`` is the byte offset to start at
- ``length`` is how many bytes to slice (if None then will slice
to the end of the data),
- ``attr_name`` is the name of the attribute corresponding to the
field
- ``callable`` is a decoding function that returns the decoded
value
- ``args`` is a list of arguments to pass ``callable``
"""
return [
((6, 2), 'protocol_version', self._wrap_unpack, [UNPACK_UINT2]),
((10, 16), 'called_ae_title', self._wrap_bytes, []),
((26, 16), 'calling_ae_title', self._wrap_bytes, []),
((74, None), 'variable_items', self._wrap_generate_items, [])
]
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ``(attr_name, callable, [args])``, where:
- ``attr_name`` is the name of the attribute corresponding to the
field
- ``callable`` is an encoding function that returns :class:`bytes`
- ``args`` is a :class:`list` of arguments to pass ``callable``.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
('protocol_version', PACK_UINT2, []),
(None, self._wrap_pack, [0x0000, PACK_UINT2]),
('called_ae_title', self._wrap_bytes, []),
('calling_ae_title', self._wrap_bytes, []),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
('variable_items', self._wrap_encode_items, [])
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as :class:`int`."""
length = 68
for item in self.variable_items:
length += len(item)
return length
@property
def presentation_context(self):
"""Return a list of the Presentation Context items.
Returns
-------
list of pdu_items.PresentationContextItemRQ
The Presentation Context items.
"""
return [item for item in self.variable_items if
isinstance(item, PresentationContextItemRQ)]
def __str__(self):
"""Return a string representation of the PDU."""
s = 'A-ASSOCIATE-RQ PDU\n'
s += '==================\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
s += f' Protocol version: {self.protocol_version:d}\n'
s += f' Called AET: {self.called_ae_title}\n'
s += f' Calling AET: {self.calling_ae_title}\n'
s += '\n'
s += ' Variable Items:\n'
s += ' ---------------\n'
s += ' * Application Context Item\n'
s += f' - Context name: ={self.application_context_name}\n'
s += ' * Presentation Context Item(s):\n'
for ii in self.presentation_context:
item_str = f'{ii}'
item_str_list = item_str.split('\n')
s += f' - {item_str_list[0]}\n'
for jj in item_str_list[1:-1]:
s += f' {jj}\n'
s += ' * User Information Item(s):\n'
for ii in self.user_information.user_data:
item_str = f'{ii}'
item_str_list = item_str.split('\n')
s += f' - {item_str_list[0]}\n'
for jj in item_str_list[1:-1]:
s += f' {jj}\n'
return s
@property
def user_information(self):
"""Return the User Information Item, if available.
Returns
-------
pdu_items.UserInformationItem or None
The requestor's User Information object or ``None``, if not
available.
"""
for item in self.variable_items:
if isinstance(item, UserInformationItem):
return item
return None
class A_ASSOCIATE_AC(PDU):
"""An A-ASSOCIATE-AC PDU.
An A-ASSOCIATE-AC PDU is sent by an association acceptor to indicate that
association negotiation has been successful.
Attributes
----------
application_context_name : pydicom.uid.UID
The Application Context Item's *Application Context Name* field value
(if available).
called_ae_title : bytes
The requestor's *Called AE Title* field value, which is the destination
DICOM application name as a 16-byte value. The value is not
guaranteed to be the actual title and shall not be tested.
calling_ae_title : bytes
The requestor's *Calling AE Title* field value, which is the source
DICOM application name as a 16-byte value. The value is not
guaranteed to be the actual title and shall not be tested.
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x02``).
presentation_context : list of pdu_items.PresentationContextItemAC
The *Presentation Context Item(s)*.
protocol_version : int
The *Protocol Version* field value (default ``0x01``).
user_information : pdu_items.UserInformationItem
The *User Information Item* (if available).
variable_items : list
A list containing the A-ASSOCIATE-AC's 'Variable Items'. Contains
one Application Context item, one or more Presentation Context items
and one User Information item. The order of the items is not
guaranteed.
Notes
-----
An A-ASSOCIATE-AC PDU requires the following parameters:
* PDU type (1, fixed value, ``0x02``)
* PDU length (1)
* Protocol version (1, default value, ``0x01``)
* Variable items (1)
* Application Context Item (1)
* Item type (1, fixed value, ``0x10``)
* Item length (1)
* Application Context Name (1, fixed in an application)
* Presentation Context Item(s) (1 or more)
* Item type (1, fixed value, ``0x21``)
* Item length (1)
* Context ID (1)
* Result/reason (1)
* Transfer Syntax Sub-items (1)
* Item type (1, fixed, ``0x40``)
* Item length (1)
* Transfer syntax name(s) (1)
* User Information Item (1)
* Item type (1, fixed, ``0x50``)
* Item length (1)
* User data Sub-items (2 or more)
* Maximum Length Received Sub-item (1)
* Implementation Class UID Sub-item (1)
* Optional User Data Sub-items (0 or more)
**Encoding**
When encoded, an A-ASSOCIATE-AC PDU has the following structure, taken
from Table 9-17 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+------------------+
| Offset | Length | Description |
+========+=============+==================+
| 0 | 1 | PDU type |
+--------+-------------+------------------+
| 1 | 1 | Reserved |
+--------+-------------+------------------+
| 2 | 4 | PDU length |
+--------+-------------+------------------+
| 6 | 2 | Protocol version |
+--------+-------------+------------------+
| 8 | 2 | Reserved |
+--------+-------------+------------------+
| 10 | 16 | Reserved^ |
+--------+-------------+------------------+
| 26 | 16 | Reserved^ |
+--------+-------------+------------------+
| 42 | 32 | Reserved |
+--------+-------------+------------------+
| 74 | Variable | Variable items |
+--------+-------------+------------------+
^ The reserved fields shall be sent with a value identical to the value
received in the A-ASSOCIATE-RQ but their values shall not be tested.
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.3 <part08/sect_9.3.3.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-ASSOCIATE-AC PDU."""
# We allow the user to modify the protocol version if so desired
self.protocol_version = 0x01
# Called AE Title, should be present, but no guarantees
self._reserved_aet = None
# Calling AE Title, should be present, but no guarantees
self._reserved_aec = None
# `variable_items` is a list containing the following:
# 1 ApplicationContextItem
# 1 or more PresentationContextItemAC
# 1 UserInformationItem
# The order of the items in the list may not be as given above
self.variable_items = []
def from_primitive(self, primitive):
"""Setup the current PDU using an A-ASSOCIATE (accept) primitive.
Parameters
----------
primitive : pdu_primitives.A_ASSOCIATE
The primitive to use to set the current PDU field values.
"""
self._reserved_aet = primitive.called_ae_title
self._reserved_aec = primitive.calling_ae_title
# Make application context
application_context = ApplicationContextItem()
application_context.application_context_name = (
primitive.application_context_name
)
self.variable_items.append(application_context)
# Make presentation contexts
for ii in primitive.presentation_context_definition_results_list:
presentation_context = PresentationContextItemAC()
presentation_context.from_primitive(ii)
self.variable_items.append(presentation_context)
# Make user information
user_information = UserInformationItem()
user_information.from_primitive(primitive.user_information)
self.variable_items.append(user_information)
def to_primitive(self):
"""Return an A-ASSOCIATE (accept) primitive from the current PDU.
Returns
-------
pdu_primitives.A_ASSOCIATE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ASSOCIATE
primitive = A_ASSOCIATE()
# The two reserved parameters at byte offsets 11 and 27 shall be set
# to called and calling AET byte the value shall not be
# tested when received (PS3.8 Table 9-17)
primitive.called_ae_title = self._reserved_aet
primitive.calling_ae_title = self._reserved_aec
for item in self.variable_items:
# Add application context
if isinstance(item, ApplicationContextItem):
primitive.application_context_name = (
item.application_context_name
)
# Add presentation contexts
elif isinstance(item, PresentationContextItemAC):
primitive.presentation_context_definition_results_list.append(
item.to_primitive()
)
# Add user information
elif isinstance(item, UserInformationItem):
primitive.user_information = item.to_primitive()
# 0x00 = Accepted
primitive.result = 0x00
return primitive
@property
def application_context_name(self):
"""Return the *Application Context Name*, if available.
Returns
-------
pydicom.uid.UID or None
The acceptor's *Application Context Name* or None if not available.
"""
for item in self.variable_items:
if isinstance(item, ApplicationContextItem):
return item.application_context_name
return None
@property
def called_ae_title(self):
"""Return the value sent in the *Called AE Title* reserved space.
While the standard says this value should match the A-ASSOCIATE-RQ
value there is no guarantee and this should not be used as a check
value.
Returns
-------
bytes
The value the A-ASSOCIATE-AC sent in the *Called AE Title* reserved
space.
"""
return self._reserved_aet
@property
def calling_ae_title(self):
"""Return the value sent in the *Calling AE Title* reserved space.
While the standard says this value should match the A-ASSOCIATE-RQ
value there is no guarantee and this should not be used as a check
value.
Returns
-------
bytes
The value the A-ASSOCIATE-AC sent in the *Calling AE Title*
reserved space.
"""
return self._reserved_aec
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return [
((6, 2), 'protocol_version', self._wrap_unpack, [UNPACK_UINT2]),
((10, 16), '_reserved_aet', self._wrap_bytes, []),
((26, 16), '_reserved_aec', self._wrap_bytes, []),
((74, None), 'variable_items', self._wrap_generate_items, [])
]
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
('protocol_version', PACK_UINT2, []),
(None, self._wrap_pack, [0x0000, PACK_UINT2]),
('_reserved_aet', self._wrap_bytes, []),
('_reserved_aec', self._wrap_bytes, []),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
('variable_items', self._wrap_encode_items, [])
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
length = 68
for item in self.variable_items:
length += len(item)
return length
@property
def presentation_context(self):
"""Return a list of the Presentation Context Items.
Returns
-------
list of pdu_items.PresentationContextItemAC
The Presentation Context Items.
"""
return [item for item in self.variable_items if
isinstance(item, PresentationContextItemAC)]
def __str__(self):
"""Return a string representation of the PDU."""
s = 'A-ASSOCIATE-AC PDU\n'
s += '==================\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
s += f' Protocol version: {self.protocol_version:d}\n'
s += f' Reserved (Called AET): {self._reserved_aet}\n'
s += f' Reserved (Calling AET): {self._reserved_aec}\n'
s += '\n'
s += ' Variable Items:\n'
s += ' ---------------\n'
s += ' * Application Context Item\n'
s += f' - Context name: ={self.application_context_name}\n'
s += ' * Presentation Context Item(s):\n'
for ii in self.presentation_context:
item_str = f'{ii}'
item_str_list = item_str.split('\n')
s += f' - {item_str_list[0]}\n'
for jj in item_str_list[1:-1]:
s += f' {jj}\n'
s += ' * User Information Item(s):\n'
for item in self.user_information.user_data:
item_str = f'{item}'
item_str_list = item_str.split('\n')
s += f' - {item_str_list[0]}\n'
for jj in item_str_list[1:-1]:
s += f' {jj}\n'
return s
@property
def user_information(self):
"""Return the User Information Item, if available.
Returns
-------
pdu_items.UserInformationItem or None
The acceptor's User Information object or None, if not available.
"""
for item in self.variable_items:
if isinstance(item, UserInformationItem):
return item
return None
class A_ASSOCIATE_RJ(PDU):
"""An A-ASSOCIATE-RJ PDU.
An A-ASSOCIATE-RJ PDU is sent by an association acceptor to indicate that
association negotiation has been unsuccessful.
Attributes
----------
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x03``).
reason_diagnostic : int
The *Reason/Diagnostic* field value.
result : int
The *Result* field value.
source : int
The *Source* field value.
Notes
-----
An A-ASSOCIATE-RJ PDU requires the following parameters:
* PDU type (1, fixed value, ``0x03``)
* PDU length (1)
* Result (1)
* Source (1)
* Reason/Diagnostic (1)
**Encoding**
When encoded, an A-ASSOCIATE-RJ PDU has the following structure, taken
from Table 9-21 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+-------------------+
| Offset | Length | Description |
+========+=============+===================+
| 0 | 1 | PDU type |
+--------+-------------+-------------------+
| 1 | 1 | Reserved |
+--------+-------------+-------------------+
| 2 | 4 | PDU length |
+--------+-------------+-------------------+
| 6 | 1 | Reserved |
+--------+-------------+-------------------+
| 7 | 1 | Result |
+--------+-------------+-------------------+
| 8 | 1 | Source |
+--------+-------------+-------------------+
| 9 | 1 | Reason/diagnostic |
+--------+-------------+-------------------+
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.4 <part08/sect_9.3.4.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-ASSOCIATE-RJ PDU."""
self.result = None
self.source = None
self.reason_diagnostic = None
def from_primitive(self, primitive):
"""Setup the current PDU using an A-ASSOCIATE (reject) primitive.
Parameters
----------
primitive : pdu_primitives.A_ASSOCIATE
The primitive to use to set the current PDU field values.
"""
self.result = primitive.result
self.source = primitive.result_source
self.reason_diagnostic = primitive.diagnostic
def to_primitive(self):
"""Return an A-ASSOCIATE (reject) primitive from the current PDU.
Returns
-------
pdu_primitives.A_ASSOCIATE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ASSOCIATE
primitive = A_ASSOCIATE()
primitive.result = self.result
primitive.result_source = self.source
primitive.diagnostic = self.reason_diagnostic
return primitive
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return [
((7, 1), 'result', self._wrap_unpack, [UNPACK_UCHAR]),
((8, 1), 'source', self._wrap_unpack, [UNPACK_UCHAR]),
((9, 1), 'reason_diagnostic', self._wrap_unpack, [UNPACK_UCHAR])
]
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('result', PACK_UCHAR, []),
('source', PACK_UCHAR, []),
('reason_diagnostic', PACK_UCHAR, []),
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
return 4
@property
def reason_str(self):
"""Return a str describing the *Reason/Diagnostic* field value."""
_reasons = {
1 : {
1 : "No reason given",
2 : "Application context name not supported",
3 : "Calling AE title not recognised",
4 : "Reserved",
5 : "Reserved",
6 : "Reserved",
7 : "Called AE title not recognised",
8 : "Reserved",
9 : "Reserved",
10 : "Reserved"
},
2 : {
1 : "No reason given",
2 : "Protocol version not supported"
},
3 : {
0 : "Reserved",
1 : "Temporary congestion",
2 : "Local limit exceeded",
3 : "Reserved",
4 : "Reserved",
5: "Reserved",
6 : "Reserved",
7 : "Reserved"
}
}
if self.source not in _reasons:
LOGGER.error('Invalid value in Source field in '
'A-ASSOCIATE-RJ PDU')
raise ValueError('Invalid value in Source field in '
'A-ASSOCIATE-RJ PDU')
if self.reason_diagnostic not in _reasons[self.source]:
LOGGER.error('Invalid value in Reason field in '
'A-ASSOCIATE-RJ PDU')
raise ValueError('Invalid value in Reason field in '
'A-ASSOCIATE-RJ PDU')
return _reasons[self.source][self.reason_diagnostic]
@property
def result_str(self):
"""Return a str describing the *Result* field value."""
_results = {
1 : 'Rejected (Permanent)',
2 : 'Rejected (Transient)'
}
if self.result not in _results:
LOGGER.error('Invalid value in Result field in '
'A-ASSOCIATE-RJ PDU')
raise ValueError('Invalid value in Result field in '
'A-ASSOCIATE-RJ PDU')
return _results[self.result]
@property
def source_str(self):
"""Return a str describing the *Source* field value."""
_sources = {
1 : 'DUL service-user',
2 : 'DUL service-provider (ACSE related)',
3 : 'DUL service-provider (presentation related)'
}
if self.source not in _sources:
LOGGER.error('Invalid value in Source field in '
'A-ASSOCIATE-RJ PDU')
raise ValueError('Invalid value in Source field in '
'A-ASSOCIATE-RJ PDU')
return _sources[self.source]
def __str__(self):
"""Return a string representation of the PDU."""
s = 'A-ASSOCIATE-RJ PDU\n'
s += '==================\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
s += f' Result: {self.result_str}\n'
s += f' Source: {self.source_str}\n'
s += f' Reason/Diagnostic: {self.reason_str}\n'
return s
# Overridden _generate_items and _wrap_generate_items
class P_DATA_TF(PDU):
"""A P-DATA-TF PDU.
A P-DATA-TF PDU is used once an association has been established to send
DIMSE message data.
Attributes
----------
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x04``).
presentation_data_value_items : list of pdu.PresentationDataValueItem
The *Presentation Data Value Item(s)* field value.
Notes
-----
A P-DATA-TF PDU requires the following parameters:
* PDU type (1, fixed value, ``0x04``)
* PDU length (1)
* Presentation data value Item(s) (1 or more)
**Encoding**
When encoded, a P-DATA-TF PDU has the following structure, taken
from Table 9-22 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+-------------------------------+
| Offset | Length | Description |
+========+=============+===============================+
| 0 | 1 | PDU type |
+--------+-------------+-------------------------------+
| 1 | 1 | Reserved |
+--------+-------------+-------------------------------+
| 2 | 4 | PDU length |
+--------+-------------+-------------------------------+
| 6 | Variable | Presentation data value items |
+--------+-------------+-------------------------------+
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.5 <part08/sect_9.3.5.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new P-DATA-TF PDU."""
self.presentation_data_value_items = []
def from_primitive(self, primitive):
"""Setup the current PDU using a P-DATA primitive.
Parameters
----------
primitive : pdu_primitives.P_DATA
The primitive to use to set the current PDU field values.
"""
for item in primitive.presentation_data_value_list:
presentation_data_value = PresentationDataValueItem()
presentation_data_value.presentation_context_id = item[0]
presentation_data_value.presentation_data_value = item[1]
self.presentation_data_value_items.append(presentation_data_value)
def to_primitive(self):
"""Return a P-DATA primitive from the current PDU.
Returns
-------
pdu_primitives.P_DATA
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import P_DATA
primitive = P_DATA()
primitive.presentation_data_value_list = []
for item in self.presentation_data_value_items:
primitive.presentation_data_value_list.append(
[item.presentation_context_id, item.presentation_data_value]
)
return primitive
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return [
((6, None),
'presentation_data_value_items',
self._wrap_generate_items,
[])
]
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
('presentation_data_value_items', self._wrap_encode_items, [])
]
@staticmethod
def _generate_items(bytestream):
"""Yield the variable PDV item data from `bytestream`.
Parameters
----------
bytestream : bytes
The encoded PDU variable item data.
Yields
------
int, bytes
The PDV's Presentation Context ID as int, and the PDV item's
encoded data as bytes.
Notes
-----
**Encoding**
When encoded, a Presentation Data Value Item has the following
structure, taken from Table 9-23 (offset shown with Python
indexing). The item is encoded using Big Endian, but the encoding of
of the presentation data message fragments is dependent on the
negotiated transfer syntax.
+--------+-------------+-------------------------+
| Offset | Length | Description |
+========+=============+=========================+
| 0 | 4 | Item length |
+--------+-------------+-------------------------+
| 4 | 1 | Context ID |
+--------+-------------+-------------------------+
| 5 | NN | Presentation data value |
+--------+-------------+-------------------------+
References
----------
* DICOM Standard, Part 8, :dcm:`Section
9.3.5.1 <part08/sect_9.3.5.html#sect_9.3.5.1>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
offset = 0
while bytestream[offset:offset + 1]:
item_length = UNPACK_UINT4(bytestream[offset:offset + 4])[0]
context_id = UNPACK_UCHAR(bytestream[offset + 4:offset + 5])[0]
data = bytestream[offset + 5:offset + 4 + item_length]
assert len(data) == item_length - 1
yield context_id, data
# Change `offset` to the start of the next PDV item
offset += 4 + item_length
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
length = 0
for item in self.presentation_data_value_items:
length += len(item)
return length
def __str__(self):
"""Return a string representation of the PDU."""
s = 'P-DATA-TF PDU\n'
s += '=============\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
s += '\n'
s += ' Presentation Data Value Item(s):\n'
s += ' --------------------------------\n'
for ii in self.presentation_data_value_items:
item_str = f'{ii}'
item_str_list = item_str.split('\n')
s += f' * {item_str_list[0]}\n'
for jj in item_str_list[1:-1]:
s += f' {jj}\n'
return s
def _wrap_generate_items(self, bytestream):
"""Return a list of PDV Items generated from `bytestream`.
Parameters
----------
bytestream : bytes
The encoded presentation data value items.
Returns
-------
list of pdu_items.PresentationDataValueItem
The presentation data value items contained in `bytestream`.
"""
item_list = []
for context_id, data in self._generate_items(bytestream):
pdv_item = PresentationDataValueItem()
pdv_item.presentation_context_id = context_id
pdv_item.presentation_data_value = data
item_list.append(pdv_item)
return item_list
class A_RELEASE_RQ(PDU):
"""An A-RELEASE-RQ PDU.
An A-RELEASE-RQ PDU is used once an association has been established to
initiate the release of the association.
Attributes
----------
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x05``).
Notes
-----
An A-RELEASE-RQ PDU requires the following parameters:
* PDU type (1, fixed value, ``0x05``)
* PDU length (1, fixed value, 4)
**Encoding**
When encoded, an A-RELEASE-RQ PDU has the following structure, taken
from Table 9-24 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+---------------+
| Offset | Length | Description |
+========+=============+===============+
| 0 | 1 | PDU type |
+--------+-------------+---------------+
| 1 | 1 | Reserved |
+--------+-------------+---------------+
| 2 | 4 | PDU length |
+--------+-------------+---------------+
| 6 | 4 | Reserved |
+--------+-------------+---------------+
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.6 <part08/sect_9.3.6.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-RELEASE-RQ PDU."""
pass
@staticmethod
def from_primitive(primitive):
"""Setup the current PDU using an A-RELEASE (request) primitive.
Parameters
----------
primitive : pdu_primitives.A_RELEASE
The primitive to use to set the current PDU field values.
"""
pass
@staticmethod
def to_primitive():
"""Return an A-RELEASE (request) primitive from the current PDU.
Returns
-------
pdu_primitives.A_RELEASE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_RELEASE
return A_RELEASE()
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return []
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
(None, self._wrap_pack, [0x00, PACK_UINT4])
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
return 4
def __str__(self):
"""Return a string representation of the PDU."""
s = 'A-RELEASE-RQ PDU\n'
s += '================\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
return s
class A_RELEASE_RP(PDU):
"""An A-RELEASE-RP PDU.
An A-RELEASE-RP PDU is used once an association has been established to
confirm the release of the association.
Attributes
----------
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x06``).
Notes
-----
An A-RELEASE-RP PDU requires the following parameters:
* PDU type (1, fixed value, ``0x06``)
* PDU length (1, fixed value, ``0x00000004``)
**Encoding**
When encoded, an A-RELEASE-RP PDU has the following structure, taken
from Table 9-25 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+---------------+
| Offset | Length | Description |
+========+=============+===============+
| 0 | 1 | PDU type |
+--------+-------------+---------------+
| 1 | 1 | Reserved |
+--------+-------------+---------------+
| 2 | 4 | PDU length |
+--------+-------------+---------------+
| 6 | 4 | Reserved |
+--------+-------------+---------------+
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.7 <part08/sect_9.3.7.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-RELEASE-RP PDU."""
pass
@staticmethod
def from_primitive(primitive):
"""Setup the current PDU using an A-release (response) primitive.
Parameters
----------
primitive : pdu_primitives.A_RELEASE
The primitive to use to set the current PDU field values.
"""
pass
@staticmethod
def to_primitive():
"""Return an A-RELEASE (response) primitive from the current PDU.
Returns
-------
pdu_primitives.A_RELEASE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_RELEASE
primitive = A_RELEASE()
primitive.result = 'affirmative'
return primitive
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return []
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
(None, self._wrap_pack, [0x00, PACK_UINT4])
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
return 4
def __str__(self):
"""Return a string representation of the PDU."""
s = 'A-RELEASE-RP PDU\n'
s += '================\n'
s += f' PDU type: 0x{self.pdu_type:02x}\n'
s += f' PDU length: {self.pdu_length:d} bytes\n'
return s
class A_ABORT_RQ(PDU):
"""An A-ABORT-RQ PDU.
An A-ABORT-RQ PDU is used to abort the association.
Attributes
----------
pdu_length : int
The number of bytes from the first byte following the *PDU Length*
field to the last byte of the PDU.
pdu_type : int
The *PDU Type* field value (``0x07``).
reason_diagnostic : int
The *Reason/Diagnostic* field value.
source : int
The *Source* field value.
Notes
-----
An A-ABORT-RQ PDU requires the following parameters:
* PDU type (1, fixed value, ``0x06``)
* PDU length (1, fixed value, 4)
* Source (1)
* Reason/Diagnostic (1)
**Encoding**
When encoded, an A-ABORT-RQ PDU has the following structure, taken
from Table 9-26 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+-------------------+
| Offset | Length | Description |
+========+=============+===================+
| 0 | 1 | PDU type |
+--------+-------------+-------------------+
| 1 | 1 | Reserved |
+--------+-------------+-------------------+
| 2 | 4 | PDU length |
+--------+-------------+-------------------+
| 6 | 1 | Reserved |
+--------+-------------+-------------------+
| 7 | 1 | Reserved |
+--------+-------------+-------------------+
| 8 | 1 | Source |
+--------+-------------+-------------------+
| 9 | 1 | Reason/Diagnostic |
+--------+-------------+-------------------+
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.8 <part08/sect_9.3.8.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self):
"""Initialise a new A-ABORT-RQ PDU."""
self.source = None
self.reason_diagnostic = None
def from_primitive(self, primitive):
"""Setup the current PDU using an A-ABORT or A-P-ABORT primitive.
Parameters
----------
primitive : pdu_primitives.A_ABORT or pdu_primitives.A_P_ABORT
The primitive to use to set the current PDU field values.
"""
from pynetdicom.pdu_primitives import A_ABORT, A_P_ABORT
# User initiated abort
if primitive.__class__ == A_ABORT:
# The reason field shall be 0x00 when the source is DUL
# service-user
self.reason_diagnostic = 0
self.source = primitive.abort_source
# User provider primitive abort
elif primitive.__class__ == A_P_ABORT:
self.reason_diagnostic = primitive.provider_reason
self.source = 2
def to_primitive(self):
"""Return an A-ABORT or A-P-ABORT primitive from the current PDU.
Returns
-------
pdu_primitives.A_ABORT or pdu_primitives.A_P_ABORT
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ABORT, A_P_ABORT
# User initiated abort
if self.source == 0x00:
primitive = A_ABORT()
primitive.abort_source = self.source
# User provider primitive abort
elif self.source == 0x02:
primitive = A_P_ABORT()
primitive.provider_reason = self.reason_diagnostic
return primitive
@property
def _decoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return [
((8, 1), 'source', self._wrap_unpack, [UNPACK_UCHAR]),
((9, 1), 'reason_diagnostic', self._wrap_unpack, [UNPACK_UCHAR])
]
@property
def _encoders(self):
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where
- attr_name is the name of the attribute corresponding to the field
- callable is an encoding function that returns bytes
- args is a list of arguments to pass callable.
"""
return [
('pdu_type', PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('pdu_length', PACK_UINT4, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
('source', PACK_UCHAR, []),
('reason_diagnostic', PACK_UCHAR, []),
]
@property
def pdu_length(self):
"""Return the *PDU Length* field value as an int."""
return 4
def __str__(self):
"""Return a string representation of the PDU."""
s = "A-ABORT PDU\n"
s += "===========\n"
s += f" PDU type: 0x{self.pdu_type:02x}\n"
s += f" PDU length: {self.pdu_length:d} bytes\n"
s += f" Abort Source: {self.source_str}\n"
s += f" Reason/Diagnostic: {self.reason_str}\n"
return s
@property
def source_str(self):
"""Return a str description of the *Source* field value."""
_sources = {
0 : 'DUL service-user',
1 : 'Reserved',
2 : 'DUL service-provider'
}
return _sources[self.source]
@property
def reason_str(self):
"""Return a str description of the *Reason/Diagnostic* field value."""
if self.source == 2:
_reason_str = {
0 : "No reason given",
1 : "Unrecognised PDU",
2 : "Unexpected PDU",
3 : "Reserved",
4 : "Unrecognised PDU parameter",
5 : "Unexpected PDU parameter",
6 : "Invalid PDU parameter value"
}
return _reason_str[self.reason_diagnostic]
return 'No reason given'
# PDUs indexed by their class
PDU_TYPES = {
A_ASSOCIATE_RQ : 0x01,
A_ASSOCIATE_AC : 0x02,
A_ASSOCIATE_RJ : 0x03,
P_DATA_TF : 0x04,
A_RELEASE_RQ : 0x05,
A_RELEASE_RP : 0x06,
A_ABORT_RQ : 0x07,
}
|
scaramallion/pynetdicom3
|
pynetdicom/pdu.py
|
Python
|
mit
| 68,107
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib import script
import random
rand = random.randint
def warp_uptown_east(pc):
result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp")
if result == 1:
script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン
elif result == 2:
script.warp(pc, 10023400, rand(126, 129), rand(29, 32)) #アップタウン北可動橋
elif result == 3:
script.warp(pc, 10023300, rand(126, 129), rand(224, 227)) #アップタウン南可動橋
elif result == 4:
script.warp(pc, 10023200, rand(29, 32), rand(126, 129)) #アップタウン西可動橋
def warp_uptown_west(pc):
result = script.select(pc, ("enter", "north", "east", "south", "cancel"), "warp")
if result == 1:
script.warp(pc, 10023000, rand(37, 38), rand(126, 129)) #アップタウン
elif result == 2:
script.warp(pc, 10023400, rand(126, 129), rand(29, 32)) #アップタウン北可動橋
elif result == 3:
script.warp(pc, 10023100, rand(224, 227), rand(126, 129)) #アップタウン東可動橋
elif result == 4:
script.warp(pc, 10023300, rand(126, 129), rand(224, 227)) #アップタウン南可動橋
def warp_uptown_south(pc):
result = script.select(pc, ("enter", "north", "east", "west", "cancel"), "warp")
if result == 1:
script.warp(pc, 10023000, rand(126, 129), rand(37, 38)) #アップタウン
elif result == 2:
script.warp(pc, 10023400, rand(126, 129), rand(29, 32)) #アップタウン北可動橋
elif result == 3:
script.warp(pc, 10023100, rand(224, 227), rand(126, 129)) #アップタウン東可動橋
elif result == 4:
script.warp(pc, 10023200, rand(29, 32), rand(126, 129)) #アップタウン西可動橋
def warp_uptown_north(pc):
result = script.select(pc, ("enter", "east", "south", "west", "cancel"), "warp")
if result == 1:
script.warp(pc, 10023000, rand(126, 129), rand(37, 38)) #アップタウン
elif result == 2:
script.warp(pc, 10023100, rand(224, 227), rand(126, 129)) #アップタウン東可動橋
elif result == 3:
script.warp(pc, 10023300, rand(126, 129), rand(224, 227)) #アップタウン南可動橋
elif result == 4:
script.warp(pc, 10023200, rand(29, 32), rand(126, 129)) #アップタウン西可動橋
def warp_guild_lobby(pc):
result = script.select(pc, ("1f", "2f", "3f", "4f", "5f", "cancel"), "warp")
if result == 1:
script.warp(pc, 30110000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー1F
elif result == 2:
script.warp(pc, 30111000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー2F
elif result == 3:
script.warp(pc, 30112000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー3F
elif result == 4:
script.warp(pc, 30113000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー4F
elif result == 5:
script.warp(pc, 30114000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー5F
def warp_10000700(pc):
script.effect(pc, 4023)
script.wait(pc, 1000)
script.warp(pc, 20015000, 9, 36) #アイシー島への地下通路
def warp_10000817(pc):
result = script.select(pc, ("中立の島", "海賊の島", "聖女の島", "やっぱやめた"), "どこにする?")
if result == 1:
script.warp(pc, 10054100, 224, 86) #フシギ団の砦(北部)
elif result == 2:
script.warp(pc, 10054100, 123, 77) #フシギ団の砦(北部)
elif result == 3:
script.warp(pc, 10054000, 72, 140) #フシギ団の砦
def warp_10001723(pc):
script.say(pc, "".join(
"上にあるクジラの口まで$R;",
"ロープが伸びている…$R;",
"$R伝って登れば、$R;",
"クジラの口の中に入れそうだ。$R;"
), "warp")
result = script.select(pc, ("登らない", "登ってみる"), "登る?")
if result == 2:
script.warp(pc, 21190000, 32, 184) #口内淵
ID = {
10000003: warp_uptown_east, #アップタウン東可動橋
10000013: warp_uptown_west, #アップタウン西可動橋
10000023: warp_uptown_south, #アップタウン南可動橋
10000033: warp_uptown_north, #アップタウン北可動橋
10000164: warp_guild_lobby, #ギルド元宮ロビー1F
10000165: warp_guild_lobby, #ギルド元宮ロビー2F
10000166: warp_guild_lobby, #ギルド元宮ロビー3F
10000167: warp_guild_lobby, #ギルド元宮ロビー4F
10000168: warp_guild_lobby, #ギルド元宮ロビー5F
10000228: (30113000, 25, 13), #アルケミストギルド→ギルド元宮ロビー4F
10000229: (30113000, 1, 13), #マリオネストギルド→ギルド元宮ロビー4F
10000230: (30113000, 13, 25), #レンジャーギルド→ギルド元宮ロビー4F
10000231: (30113000, 13, 1), #マーチャントギルド→ギルド元宮ロビー4F
10000432: (30020001, 3, 5), #イストー岬→民家
10000600: (30010001, 3, 5), #ノーザンプロムナード→ノーザン酒屋
#10000624: None,
#10000632: None,
#10000634: None,
10000638: (30170000, 3, 6), #永遠への北限→イグルー
10000483: (10051000, 96, 123), #アイシー島→永遠への北限
10000700: warp_10000700, #アイシー島への地下通路
10000769: (30077000, 8, 12), #アイアンシティ下層階→動力制御室
10000817: warp_10000817, #フシギ団本部
10001317: (30091001, 6, 15), #東アクロニア平原→東平原初心者学校
10001318: (10025000, 108, 123), #東平原初心者学校→東アクロニア平原
10001319: (30091002, 6, 15), #西アクロニア平原→西平原初心者学校
10001320: (10022000, 143, 133), #西平原初心者学校→西アクロニア平原
10001321: (30091003, 6, 15), #南アクロニア平原→南平原初心者学校
10001322: (10031000, 132, 121), #南平原初心者学校→南アクロニア平原
10001323: (30091004, 6, 15), #北アクロニア平原→北平原初心者学校
10001324: (30091004, 6, 15), #北平原初心者学校→北アクロニア平原
10001723: warp_10001723,
12001118: (30131001, 6, 1), #フシギ団の砦→フシギ団本部
}
def main(pc):
warp_info = ID[pc.event_id]
if callable(warp_info):
warp_info(pc)
return
map_id = warp_info[0]
if len(warp_info) == 3:
x = warp_info[1]
y = warp_info[2]
else:
x = random.randint(warp_info[1], warp_info[3])
y = random.randint(warp_info[2], warp_info[4])
script.warp(pc, map_id, x, y)
#Copyright (C) ゆとり鯖 All Rights Reserved.
|
twinpa/virtualeco
|
script/site_packages/warp_event.py
|
Python
|
mit
| 6,364
|
#!/usr/bin/env python
#coding: utf-8
"""
This module simply sends request to the Digital Ocean API,
and returns their response as a dict.
"""
import requests
API_ENDPOINT = 'https://api.digitalocean.com'
class DoError(RuntimeError):
pass
class DoManager(object):
def __init__(self, client_id, api_key):
self.client_id = client_id
self.api_key = api_key
def all_active_droplets(self):
json = self.request('/droplets/')
return json['droplets']
def new_droplet(self, name, size_id, image_id, region_id,
ssh_key_ids=None, virtio=False, private_networking=False,
backups_enabled=False):
params = {
'name': name,
'size_id': size_id,
'image_id': image_id,
'region_id': region_id,
'virtio': virtio,
'private_networking': private_networking,
'backups_enabled': backups_enabled,
}
if ssh_key_ids:
params['ssh_key_ids'] = ssh_key_ids
json = self.request('/droplets/new', params=params)
return json['droplet']
def show_droplet(self, id):
json = self.request('/droplets/%s' % id)
return json['droplet']
def reboot_droplet(self, id):
json = self.request('/droplets/%s/reboot/' % id)
json.pop('status', None)
return json
def power_cycle_droplet(self, id):
json = self.request('/droplets/%s/power_cycle/' % id)
json.pop('status', None)
return json
def shutdown_droplet(self, id):
json = self.request('/droplets/%s/shutdown/' % id)
json.pop('status', None)
return json
def power_off_droplet(self, id):
json = self.request('/droplets/%s/power_off/' % id)
json.pop('status', None)
return json
def power_on_droplet(self, id):
json = self.request('/droplets/%s/power_on/' % id)
json.pop('status', None)
return json
def password_reset_droplet(self, id):
json = self.request('/droplets/%s/password_reset/' % id)
json.pop('status', None)
return json
def resize_droplet(self, id, size_id):
params = {'size_id': size_id}
json = self.request('/droplets/%s/resize/' % id, params)
json.pop('status', None)
return json
def snapshot_droplet(self, id, name):
params = {'name': name}
json = self.request('/droplets/%s/snapshot/' % id, params)
json.pop('status', None)
return json
def restore_droplet(self, id, image_id):
params = {'image_id': image_id}
json = self.request('/droplets/%s/restore/' % id, params)
json.pop('status', None)
return json
def rebuild_droplet(self, id, image_id):
params = {'image_id': image_id}
json = self.request('/droplets/%s/rebuild/' % id, params)
json.pop('status', None)
return json
def enable_backups_droplet(self, id):
json = self.request('/droplets/%s/enable_backups/' % id)
json.pop('status', None)
return json
def disable_backups_droplet(self, id):
json = self.request('/droplets/%s/disable_backups/' % id)
json.pop('status', None)
return json
def rename_droplet(self, id, name):
params = {'name': name}
json = self.request('/droplets/%s/rename/' % id, params)
json.pop('status', None)
return json
def destroy_droplet(self, id, scrub_data=True):
params = {'scrub_data': '1' if scrub_data else '0'}
json = self.request('/droplets/%s/destroy/' % id, params)
json.pop('status', None)
return json
#regions==========================================
def all_regions(self):
json = self.request('/regions/')
return json['regions']
#images==========================================
def all_images(self, filter='global'):
params = {'filter': filter}
json = self.request('/images/', params)
return json['images']
def show_image(self, image_id):
params= {'image_id': image_id}
json = self.request('/images/%s/' % image_id, params)
return json['image']
def destroy_image(self, image_id):
self.request('/images/%s/destroy' % image_id)
return True
def transfer_image(self, image_id, region_id):
params = {'region_id': region_id}
json = self.request('/images/%s/transfer/' % image_id, params)
json.pop('status', None)
return json
#ssh_keys=========================================
def all_ssh_keys(self):
json = self.request('/ssh_keys/')
return json['ssh_keys']
def new_ssh_key(self, name, pub_key):
params = {'name': name, 'ssh_pub_key': pub_key}
json = self.request('/ssh_keys/new/', params)
return json['ssh_key']
def show_ssh_key(self, key_id):
json = self.request('/ssh_keys/%s/' % key_id)
return json['ssh_key']
def edit_ssh_key(self, key_id, name, pub_key):
params = {'name': name, 'ssh_pub_key': pub_key} # the doc needs to be improved
json = self.request('/ssh_keys/%s/edit/' % key_id, params)
return json['ssh_key']
def destroy_ssh_key(self, key_id):
self.request('/ssh_keys/%s/destroy/' % key_id)
return True
#sizes============================================
def sizes(self):
json = self.request('/sizes/')
return json['sizes']
#domains==========================================
def all_domains(self):
json = self.request('/domains/')
return json['domains']
def new_domain(self, name, ip):
params = {
'name': name,
'ip_address': ip
}
json = self.request('/domains/new/', params)
return json['domain']
def show_domain(self, domain_id):
json = self.request('/domains/%s/' % domain_id)
return json['domain']
def destroy_domain(self, domain_id):
self.request('/domains/%s/destroy/' % domain_id)
return True
def all_domain_records(self, domain_id):
json = self.request('/domains/%s/records/' % domain_id)
return json['records']
def new_domain_record(self, domain_id, record_type, data, name=None, priority=None, port=None, weight=None):
params = {
'record_type': record_type,
'data': data,
}
if name: params['name'] = name
if priority: params['priority'] = priority
if port: params['port'] = port
if weight: params['weight'] = port
json = self.request('/domains/%s/records/new/' % domain_id, params)
return json['domain_record'] if 'domain_record' in json else json['record'] # DO API docs say 'domain_record', but actually it 'record'
def show_domain_record(self, domain_id, record_id):
json = self.request('/domains/%s/records/%s' % (domain_id, record_id))
return json['record']
def edit_domain_record(self, domain_id, record_id, record_type, data, name=None, priority=None, port=None, weight=None):
params = {
'record_type': record_type,
'data': data,
}
if name: params['name'] = name
if priority: params['priority'] = priority
if port: params['port'] = port
if weight: params['weight'] = port
json = self.request('/domains/%s/records/%s/edit/' % (domain_id, record_id), params)
return json['domain_record'] if 'domain_record' in json else json['record'] # DO API docs say 'domain_record' for /new/ but 'record' for /edit/.
def destroy_domain_record(self, domain_id, record_id):
return self.request('/domains/%s/records/%s/destroy/' % (domain_id, record_id))
return True
#events===========================================
def show_event(self, event_id):
json = self.request('/events/%s' % event_id)
return json['event']
#low_level========================================
def request(self, path, params={}, method='GET'):
params['client_id'] = self.client_id
params['api_key'] = self.api_key
if not path.startswith('/'):
path = '/'+path
url = API_ENDPOINT+path
try:
resp = requests.get(url, params=params, timeout=60)
json = resp.json()
except ValueError: # requests.models.json.JSONDecodeError
raise ValueError("The API server doesn't respond with a valid json")
except requests.RequestException as e: # errors from requests
raise RuntimeError(e)
if resp.status_code != requests.codes.ok:
if json:
if 'error_message' in json:
raise DoError(json['error_message'])
elif 'message' in json:
raise DoError(json['message'])
# The JSON reponse is bad, so raise an exception with the HTTP status
resp.raise_for_status()
if json.get('status') != 'OK':
raise DoError(json['error_message'])
return json
if __name__=='__main__':
import os
client_id = os.environ['DO_CLIENT_ID']
api_key = os.environ['DO_API_KEY']
do = DoManager(client_id, api_key)
import sys
fname = sys.argv[1]
import pprint
# size_id: 66, image_id: 1601, region_id: 1
pprint.pprint(getattr(do, fname)(*sys.argv[2:]))
|
chuwy/dopy
|
dopy/manager.py
|
Python
|
mit
| 9,514
|
# coding: utf8
from prov.model import ProvBundle, Namespace, Literal, PROV, XSD, Identifier
import datetime
def primer_example():
# https://github.com/lucmoreau/ProvToolbox/blob/master/prov-n/src/test/resources/prov/primer.pn
#===========================================================================
# document
g = ProvBundle()
# prefix ex <http://example/>
# prefix dcterms <http://purl.org/dc/terms/>
# prefix foaf <http://xmlns.com/foaf/0.1/>
ex = Namespace('ex', 'http://example/') # namespaces do not need to be explicitly added to a document
g.add_namespace("dcterms", "http://purl.org/dc/terms/")
g.add_namespace("foaf", "http://xmlns.com/foaf/0.1/")
# entity(ex:article, [dcterms:title="Crime rises in cities"])
g.entity(ex['article'], {'dcterms:title': "Crime rises in cities"})
# first time the ex namespace was used, it is added to the document automatically
# entity(ex:articleV1)
g.entity(ex['articleV1'])
# entity(ex:articleV2)
g.entity(ex['articleV2'])
# entity(ex:dataSet1)
g.entity(ex['dataSet1'])
# entity(ex:dataSet2)
g.entity(ex['dataSet2'])
# entity(ex:regionList)
g.entity(ex['regionList'])
# entity(ex:composition)
g.entity(ex['composition'])
# entity(ex:chart1)
g.entity(ex['chart1'])
# entity(ex:chart2)
g.entity(ex['chart2'])
# entity(ex:blogEntry)
g.entity(ex['blogEntry'])
# activity(ex:compile)
g.activity('ex:compile') # since ex is registered, it can be used like this
# activity(ex:compile2)
g.activity('ex:compile2')
# activity(ex:compose)
g.activity('ex:compose')
# activity(ex:correct, 2012-03-31T09:21:00, 2012-04-01T15:21:00)
g.activity('ex:correct', '2012-03-31T09:21:00', '2012-04-01T15:21:00') # date time can be provided as strings
# activity(ex:illustrate)
g.activity('ex:illustrate')
# used(ex:compose, ex:dataSet1, -, [ prov:role = "ex:dataToCompose"])
g.used('ex:compose', 'ex:dataSet1', other_attributes={'prov:role': "ex:dataToCompose"})
# used(ex:compose, ex:regionList, -, [ prov:role = "ex:regionsToAggregateBy"])
g.used('ex:compose', 'ex:regionList', other_attributes={'prov:role': "ex:regionsToAggregateBy"})
# wasGeneratedBy(ex:composition, ex:compose, -)
g.wasGeneratedBy('ex:composition', 'ex:compose')
# used(ex:illustrate, ex:composition, -)
g.used('ex:illustrate', 'ex:composition')
# wasGeneratedBy(ex:chart1, ex:illustrate, -)
g.wasGeneratedBy('ex:chart1', 'ex:illustrate')
# wasGeneratedBy(ex:chart1, ex:compile, 2012-03-02T10:30:00)
g.wasGeneratedBy('ex:chart1', 'ex:compile', '2012-03-02T10:30:00')
# wasGeneratedBy(ex:chart2, ex:compile2, 2012-04-01T15:21:00)
#
#
# agent(ex:derek, [ prov:type="prov:Person", foaf:givenName = "Derek",
# foaf:mbox= "<mailto:derek@example.org>"])
g.agent('ex:derek', {'prov:type': PROV["Person"], 'foaf:givenName': "Derek",
'foaf:mbox': "<mailto:derek@example.org>"})
# wasAssociatedWith(ex:compose, ex:derek, -)
g.wasAssociatedWith('ex:compose', 'ex:derek')
# wasAssociatedWith(ex:illustrate, ex:derek, -)
g.wasAssociatedWith('ex:illustrate', 'ex:derek')
#
# agent(ex:chartgen, [ prov:type="prov:Organization",
# foaf:name = "Chart Generators Inc"])
g.agent('ex:chartgen', {'prov:type': PROV["Organization"], 'foaf:name': "Chart Generators Inc"})
# actedOnBehalfOf(ex:derek, ex:chartgen, ex:compose)
g.actedOnBehalfOf('ex:derek', 'ex:chartgen', 'ex:compose')
# wasAttributedTo(ex:chart1, ex:derek)
g.wasAttributedTo('ex:chart1', 'ex:derek')
# wasGeneratedBy(ex:dataSet2, ex:correct, -)
g.wasGeneratedBy('ex:dataSet2', 'ex:correct')
# used(ex:correct, ex:dataSet1, -)
g.used('ex:correct', 'ex:dataSet1')
# wasDerivedFrom(ex:dataSet2, ex:dataSet1, [prov:type='prov:Revision'])
g.wasDerivedFrom('ex:dataSet2', 'ex:dataSet1', other_attributes={'prov:type': PROV['Revision']})
# wasDerivedFrom(ex:chart2, ex:dataSet2)
g.wasDerivedFrom('ex:chart2', 'ex:dataSet2')
# wasDerivedFrom(ex:blogEntry, ex:article, [prov:type='prov:Quotation'])
g.wasDerivedFrom('ex:blogEntry', 'ex:article', other_attributes={'prov:type': PROV['Quotation']})
# specializationOf(ex:articleV1, ex:article)
g.specializationOf('ex:articleV1', 'ex:article')
# wasDerivedFrom(ex:articleV1, ex:dataSet1)
g.wasDerivedFrom('ex:articleV1', 'ex:dataSet1')
# specializationOf(ex:articleV2, ex:article)
g.specializationOf('ex:articleV2', 'ex:article')
# wasDerivedFrom(ex:articleV2, ex:dataSet2)
g.wasDerivedFrom('ex:articleV2', 'ex:dataSet2')
# alternateOf(ex:articleV2, ex:articleV1)
g.alternateOf('ex:articleV2', 'ex:articleV1')
# endDocument
return g
def w3c_publication_1():
# https://github.com/lucmoreau/ProvToolbox/blob/master/asn/src/test/resources/prov/w3c-publication1.prov-asn
#===========================================================================
# bundle
#
# prefix ex <http://example.org/>
#
# prefix w3 <http://www.w3.org/>
# prefix tr <http://www.w3.org/TR/2011/>
# prefix process <http://www.w3.org/2005/10/Process-20051014/tr.html#>
# prefix email <https://lists.w3.org/Archives/Member/w3c-archive/>
# prefix chairs <https://lists.w3.org/Archives/Member/chairs/>
# prefix trans <http://www.w3.org/2005/08/01-transitions.html#>
# prefix rec54 <http://www.w3.org/2001/02pd/rec54#>
#
#
# entity(tr:WD-prov-dm-20111018, [ prov:type='rec54:WD' ])
# entity(tr:WD-prov-dm-20111215, [ prov:type='rec54:WD' ])
# entity(process:rec-advance, [ prov:type='prov:Plan' ])
#
#
# entity(chairs:2011OctDec/0004, [ prov:type='trans:transreq' ])
# entity(email:2011Oct/0141, [ prov:type='trans:pubreq' ])
# entity(email:2011Dec/0111, [ prov:type='trans:pubreq' ])
#
#
# wasDerivedFrom(tr:WD-prov-dm-20111215, tr:WD-prov-dm-20111018)
#
#
# activity(ex:act1,-,-,[prov:type="publish"])
# activity(ex:act2,-,-,[prov:type="publish"])
#
# wasGeneratedBy(tr:WD-prov-dm-20111018, ex:act1, -)
# wasGeneratedBy(tr:WD-prov-dm-20111215, ex:act2, -)
#
# used(ex:act1, chairs:2011OctDec/0004, -)
# used(ex:act1, email:2011Oct/0141, -)
# used(ex:act2, email:2011Dec/0111, -)
#
# agent(w3:Consortium, [ prov:type='prov:Organization' ])
#
# wasAssociatedWith(ex:act1, w3:Consortium, process:rec-advance)
# wasAssociatedWith(ex:act2, w3:Consortium, process:rec-advance)
#
# endBundle
#===========================================================================
g = ProvBundle()
g.add_namespace('ex', 'http://example.org/')
g.add_namespace('w3', 'http://www.w3.org/')
g.add_namespace('tr', 'http://www.w3.org/TR/2011/')
g.add_namespace('process', 'http://www.w3.org/2005/10/Process-20051014/tr.html#')
g.add_namespace('email', 'https://lists.w3.org/Archives/Member/w3c-archive/')
g.add_namespace('chairs', 'https://lists.w3.org/Archives/Member/chairs/')
g.add_namespace('trans', 'http://www.w3.org/2005/08/01-transitions.html#')
g.add_namespace('rec54', 'http://www.w3.org/2001/02pd/rec54#')
g.entity('tr:WD-prov-dm-20111018', {'prov:type': 'rec54:WD'})
g.entity('tr:WD-prov-dm-20111215', {'prov:type': 'rec54:WD'})
g.entity('process:rec-advance', {'prov:type': 'prov:Plan'})
g.entity('chairs:2011OctDec/0004', {'prov:type': 'trans:transreq'})
g.entity('email:2011Oct/0141', {'prov:type': 'trans:pubreq'})
g.entity('email:2011Dec/0111', {'prov:type': 'trans:pubreq'})
g.wasDerivedFrom('tr:WD-prov-dm-20111215', 'tr:WD-prov-dm-20111018')
g.activity('ex:act1', other_attributes={'prov:type': "publish"})
g.activity('ex:act2', other_attributes={'prov:type': "publish"})
g.wasGeneratedBy('tr:WD-prov-dm-20111018', 'ex:act1')
g.wasGeneratedBy('tr:WD-prov-dm-20111215', 'ex:act2')
g.used('ex:act1', 'chairs:2011OctDec/0004')
g.used('ex:act1', 'email:2011Oct/0141')
g.used('ex:act2', 'email:2011Dec/0111')
g.agent('w3:Consortium', other_attributes={'prov:type': "Organization"})
g.wasAssociatedWith('ex:act1', 'w3:Consortium', 'process:rec-advance')
g.wasAssociatedWith('ex:act2', 'w3:Consortium', 'process:rec-advance')
return g
def w3c_publication_2():
# https://github.com/lucmoreau/ProvToolbox/blob/master/asn/src/test/resources/prov/w3c-publication2.prov-asn
#===========================================================================
# bundle
#
# prefix ex <http://example.org/>
# prefix rec <http://example.org/record>
#
# prefix w3 <http://www.w3.org/TR/2011/>
# prefix hg <http://dvcs.w3.org/hg/prov/raw-file/9628aaff6e20/model/releases/WD-prov-dm-20111215/>
#
#
# entity(hg:Overview.html, [ prov:type="file in hg" ])
# entity(w3:WD-prov-dm-20111215, [ prov:type="html4" ])
#
#
# activity(ex:rcp,-,-,[prov:type="copy directory"])
#
# wasGeneratedBy(rec:g; w3:WD-prov-dm-20111215, ex:rcp, -)
#
# entity(ex:req3, [ prov:type="http://www.w3.org/2005/08/01-transitions.html#pubreq" %% xsd:anyURI ])
#
# used(rec:u; ex:rcp,hg:Overview.html,-)
# used(ex:rcp, ex:req3, -)
#
#
# wasDerivedFrom(w3:WD-prov-dm-20111215, hg:Overview.html, ex:rcp, rec:g, rec:u)
#
# agent(ex:webmaster, [ prov:type='prov:Person' ])
#
# wasAssociatedWith(ex:rcp, ex:webmaster, -)
#
# endBundle
#===========================================================================
ex = Namespace('ex', 'http://example.org/')
rec = Namespace('rec', 'http://example.org/record')
w3 = Namespace('w3', 'http://www.w3.org/TR/2011/')
hg = Namespace('hg', 'http://dvcs.w3.org/hg/prov/raw-file/9628aaff6e20/model/releases/WD-prov-dm-20111215/')
g = ProvBundle()
g.entity(hg['Overview.html'], {'prov:type': "file in hg"})
g.entity(w3['WD-prov-dm-20111215'], {'prov:type': "html4"})
g.activity(ex['rcp'], None, None, {'prov:type': "copy directory"})
g.wasGeneratedBy('w3:WD-prov-dm-20111215', 'ex:rcp', identifier=rec['g'])
g.entity('ex:req3', {'prov:type': Identifier("http://www.w3.org/2005/08/01-transitions.html#pubreq")})
g.used('ex:rcp', 'hg:Overview.html', identifier='rec:u')
g.used('ex:rcp', 'ex:req3')
g.wasDerivedFrom('w3:WD-prov-dm-20111215', 'hg:Overview.html', 'ex:rcp', 'rec:g', 'rec:u')
g.agent('ex:webmaster', {'prov:type': "Person"})
g.wasAssociatedWith('ex:rcp', 'ex:webmaster')
return g
def bundles1():
# https://github.com/lucmoreau/ProvToolbox/blob/master/prov-n/src/test/resources/prov/bundles1.provn
#===============================================================================
# document
g = ProvBundle()
# prefix ex <http://example.org/example/>
EX = Namespace("ex", "http://www.example.com/")
g.add_namespace(EX)
# prefix alice <http://example.org/alice/>
# prefix bob <http://example.org/bob/>
g.add_namespace('alice', 'http://example.org/alice/')
g.add_namespace('bob', 'http://example.org/bob/')
# entity(bob:bundle1, [prov:type='prov:Bundle'])
g.entity('bob:bundle1', {'prov:type': PROV['Bundle']})
# wasGeneratedBy(bob:bundle1, -, 2012-05-24T10:30:00)
g.wasGeneratedBy('bob:bundle1', time='2012-05-24T10:30:00')
# agent(ex:Bob)
g.agent('ex:Bob')
# wasAttributedTo(bob:bundle1, ex:Bob)
g.wasAttributedTo('bob:bundle1', 'ex:Bob')
# entity(alice:bundle2, [ prov:type='prov:Bundle' ])
g.entity('alice:bundle2', {'prov:type': PROV['Bundle']})
# wasGeneratedBy(alice:bundle2, -, 2012-05-25T11:15:00)
g.wasGeneratedBy('alice:bundle2', time='2012-05-25T11:15:00')
# agent(ex:Alice)
g.agent('ex:Alice')
# wasAttributedTo(alice:bundle2, ex:Alice)
g.wasAttributedTo('alice:bundle2', 'ex:Alice')
# bundle bob:bundle1
b1 = g.bundle('bob:bundle1')
# entity(ex:report1, [ prov:type="report", ex:version=1 ])
b1.entity('ex:report1', {'prov:type': "report", 'ex:version': 1})
# wasGeneratedBy(ex:report1, -, 2012-05-24T10:00:01)
b1.wasGeneratedBy('ex:report1', time='2012-05-24T10:00:01')
# endBundle
# bundle alice:bundle2
b2 = g.bundle('alice:bundle2')
# entity(ex:report1)
b2.entity('ex:report1')
# entity(ex:report2, [ prov:type="report", ex:version=2 ])
b2.entity('ex:report2', {'prov:type': "report", 'ex:version': 2})
# wasGeneratedBy(ex:report2, -, 2012-05-25T11:00:01)
b2.wasGeneratedBy('ex:report2', time='2012-05-25T11:00:01')
# wasDerivedFrom(ex:report2, ex:report1)
b2.wasDerivedFrom('ex:report2', 'ex:report1')
# endBundle
# endDocument
return g
def bundles2():
# https://github.com/lucmoreau/ProvToolbox/blob/master/prov-n/src/test/resources/prov/bundles2.provn
#===========================================================================
# document
g = ProvBundle()
# prefix ex <http://example.org/example/>
g.add_namespace("ex", "http://www.example.com/")
# prefix alice <http://example.org/alice/>
# prefix bob <http://example.org/bob/>
g.add_namespace('alice', 'http://example.org/alice/')
g.add_namespace('bob', 'http://example.org/bob/')
# entity(bob:bundle4, [prov:type='prov:Bundle'])
# wasGeneratedBy(bob:bundle4, -, 2012-05-24T10:30:00)
# agent(ex:Bob)
# wasAttributedTo(bob:bundle4, ex:Bob)
g.entity('bob:bundle4', {'prov:type': PROV['Bundle']})
g.wasGeneratedBy('bob:bundle4', time='2012-05-24T10:30:00')
g.agent('ex:Bob')
g.wasAttributedTo('bob:bundle4', 'ex:Bob')
# entity(alice:bundle5, [ prov:type='prov:Bundle' ])
# wasGeneratedBy(alice:bundle5, -, 2012-05-25T11:15:00)
# agent(ex:Alice)
# wasAttributedTo(alice:bundle5, ex:Alice)
g.entity('alice:bundle5', {'prov:type': PROV['Bundle']})
g.wasGeneratedBy('alice:bundle5', time='2012-05-25T11:15:00')
g.agent('ex:Alice')
g.wasAttributedTo('alice:bundle5', 'ex:Alice')
# bundle bob:bundle4
# entity(ex:report1, [ prov:type="report", ex:version=1 ])
# wasGeneratedBy(ex:report1, -, 2012-05-24T10:00:01)
# endBundle
b4 = g.bundle('bob:bundle4')
b4.entity('ex:report1', {'prov:type': "report", 'ex:version': 1})
b4.wasGeneratedBy('ex:report1', time='2012-05-24T10:00:01')
# bundle alice:bundle5
# entity(ex:report1bis)
# mentionOf(ex:report1bis, ex:report1, bob:bundle4)
# entity(ex:report2, [ prov:type="report", ex:version=2 ])
# wasGeneratedBy(ex:report2, -, 2012-05-25T11:00:01)
# wasDerivedFrom(ex:report2, ex:report1bis)
# endBundle
b5 = g.bundle('alice:bundle5')
b5.entity('ex:report1bis')
b5.mentionOf('ex:report1bis', 'ex:report1', 'bob:bundle4')
b5.entity('ex:report2', [('prov:type', "report"), ('ex:version', 2)])
b5.wasGeneratedBy('ex:report2', time='2012-05-25T11:00:01')
b5.wasDerivedFrom('ex:report2', 'ex:report1bis')
# endDocument
return g
def collections():
g = ProvBundle()
ex = Namespace('ex', 'http://example.org/')
c1 = g.collection(ex['c1'])
e1 = g.entity('ex:e1')
g.hadMember(c1, e1)
return g
def datatypes():
g = ProvBundle()
ex = Namespace('ex', 'http://example.org/')
g.add_namespace(ex)
attributes = {'ex:int': 100,
'ex:float': 100.123456,
'ex:long': 123456789000,
'ex:bool': True,
'ex:str': 'Some string',
'ex:unicode': u'Some unicode string with accents: Huỳnh Trung Đông',
'ex:timedate': datetime.datetime(2012, 12, 12, 14, 7, 48),
'ex:intstr': Literal("PROV Internationalized string", PROV["InternationalizedString"], "en"),
}
multiline = """Line1
Line2
Line3"""
attributes['ex:multi-line'] = multiline
g.entity('ex:e1', attributes)
return g
def long_literals():
g = ProvBundle()
long_uri = "http://Lorem.ipsum/dolor/sit/amet/consectetur/adipiscing/elit/Quisque/vel/sollicitudin/felis/nec/" \
"venenatis/massa/Aenean/lectus/arcu/sagittis/sit/amet/nisl/nec/varius/eleifend/sem/In/hac/habitasse/" \
"platea/dictumst/Aliquam/eget/fermentum/enim/Curabitur/auctor/elit/non/ipsum/interdum/at/orci/aliquam/"
ex = Namespace('ex', long_uri)
g.add_namespace(ex)
g.entity('ex:e1', {'prov:label': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque'
' luctus nulla vel ullamcorper. Donec sit amet ligula sit amet lorem pretium'
' rhoncus vel vel lorem. Sed at consequat metus, eget eleifend massa. Fusce a '
'facilisis turpis. Lorem volutpat.'})
return g
tests = [
('Bundle1', bundles1),
('Bundle2', bundles2),
('Primer', primer_example),
('W3C Publication 1', w3c_publication_1),
('W3C Publication 2', w3c_publication_2),
('collections', collections),
('datatypes', datatypes),
('Long literals', long_literals),
]
|
pymonger/prov-0.5.4
|
prov/model/test/examples.py
|
Python
|
mit
| 17,487
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.core.exceptions import HttpResponseError
import msrest.serialization
class AadAuthenticationParameters(msrest.serialization.Model):
"""AAD Vpn authentication type related parameters.
:param aad_tenant: AAD Vpn authentication parameter AAD tenant.
:type aad_tenant: str
:param aad_audience: AAD Vpn authentication parameter AAD audience.
:type aad_audience: str
:param aad_issuer: AAD Vpn authentication parameter AAD issuer.
:type aad_issuer: str
"""
_attribute_map = {
'aad_tenant': {'key': 'aadTenant', 'type': 'str'},
'aad_audience': {'key': 'aadAudience', 'type': 'str'},
'aad_issuer': {'key': 'aadIssuer', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AadAuthenticationParameters, self).__init__(**kwargs)
self.aad_tenant = kwargs.get('aad_tenant', None)
self.aad_audience = kwargs.get('aad_audience', None)
self.aad_issuer = kwargs.get('aad_issuer', None)
class AddressSpace(msrest.serialization.Model):
"""AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network.
:param address_prefixes: A list of address blocks reserved for this virtual network in CIDR
notation.
:type address_prefixes: list[str]
"""
_attribute_map = {
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AddressSpace, self).__init__(**kwargs)
self.address_prefixes = kwargs.get('address_prefixes', None)
class Resource(msrest.serialization.Model):
"""Common resource representation.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(Resource, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.name = None
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
class ApplicationGateway(Resource):
"""Application gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param zones: A list of availability zones denoting where the resource needs to come from.
:type zones: list[str]
:param identity: The identity of the application gateway, if configured.
:type identity: ~azure.mgmt.network.v2020_04_01.models.ManagedServiceIdentity
:param sku: SKU of the application gateway resource.
:type sku: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySku
:param ssl_policy: SSL policy of the application gateway resource.
:type ssl_policy: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslPolicy
:ivar operational_state: Operational state of the application gateway resource. Possible values
include: "Stopped", "Starting", "Running", "Stopping".
:vartype operational_state: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayOperationalState
:param gateway_ip_configurations: Subnets of the application gateway resource. For default
limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type gateway_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayIPConfiguration]
:param authentication_certificates: Authentication certificates of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type authentication_certificates:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayAuthenticationCertificate]
:param trusted_root_certificates: Trusted Root certificates of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type trusted_root_certificates:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayTrustedRootCertificate]
:param ssl_certificates: SSL certificates of the application gateway resource. For default
limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type ssl_certificates:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslCertificate]
:param frontend_ip_configurations: Frontend IP addresses of the application gateway resource.
For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type frontend_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFrontendIPConfiguration]
:param frontend_ports: Frontend ports of the application gateway resource. For default limits,
see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type frontend_ports:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFrontendPort]
:param probes: Probes of the application gateway resource.
:type probes: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProbe]
:param backend_address_pools: Backend address pool of the application gateway resource. For
default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type backend_address_pools:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendAddressPool]
:param backend_http_settings_collection: Backend http settings of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type backend_http_settings_collection:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHttpSettings]
:param http_listeners: Http listeners of the application gateway resource. For default limits,
see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type http_listeners:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayHttpListener]
:param url_path_maps: URL path map of the application gateway resource. For default limits, see
`Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type url_path_maps: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayUrlPathMap]
:param request_routing_rules: Request routing rules of the application gateway resource.
:type request_routing_rules:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRequestRoutingRule]
:param rewrite_rule_sets: Rewrite rules for the application gateway resource.
:type rewrite_rule_sets:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRewriteRuleSet]
:param redirect_configurations: Redirect configurations of the application gateway resource.
For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type redirect_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRedirectConfiguration]
:param web_application_firewall_configuration: Web application firewall configuration.
:type web_application_firewall_configuration:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayWebApplicationFirewallConfiguration
:param firewall_policy: Reference to the FirewallPolicy resource.
:type firewall_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param enable_http2: Whether HTTP2 is enabled on the application gateway resource.
:type enable_http2: bool
:param enable_fips: Whether FIPS is enabled on the application gateway resource.
:type enable_fips: bool
:param autoscale_configuration: Autoscale Configuration.
:type autoscale_configuration:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayAutoscaleConfiguration
:ivar resource_guid: The resource GUID property of the application gateway resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the application gateway resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param custom_error_configurations: Custom error configurations of the application gateway
resource.
:type custom_error_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayCustomError]
:param force_firewall_policy_association: If true, associates a firewall policy with an
application gateway regardless whether the policy differs from the WAF Config.
:type force_firewall_policy_association: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'operational_state': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'identity': {'key': 'identity', 'type': 'ManagedServiceIdentity'},
'sku': {'key': 'properties.sku', 'type': 'ApplicationGatewaySku'},
'ssl_policy': {'key': 'properties.sslPolicy', 'type': 'ApplicationGatewaySslPolicy'},
'operational_state': {'key': 'properties.operationalState', 'type': 'str'},
'gateway_ip_configurations': {'key': 'properties.gatewayIPConfigurations', 'type': '[ApplicationGatewayIPConfiguration]'},
'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[ApplicationGatewayAuthenticationCertificate]'},
'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[ApplicationGatewayTrustedRootCertificate]'},
'ssl_certificates': {'key': 'properties.sslCertificates', 'type': '[ApplicationGatewaySslCertificate]'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[ApplicationGatewayFrontendIPConfiguration]'},
'frontend_ports': {'key': 'properties.frontendPorts', 'type': '[ApplicationGatewayFrontendPort]'},
'probes': {'key': 'properties.probes', 'type': '[ApplicationGatewayProbe]'},
'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'},
'backend_http_settings_collection': {'key': 'properties.backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHttpSettings]'},
'http_listeners': {'key': 'properties.httpListeners', 'type': '[ApplicationGatewayHttpListener]'},
'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[ApplicationGatewayUrlPathMap]'},
'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[ApplicationGatewayRequestRoutingRule]'},
'rewrite_rule_sets': {'key': 'properties.rewriteRuleSets', 'type': '[ApplicationGatewayRewriteRuleSet]'},
'redirect_configurations': {'key': 'properties.redirectConfigurations', 'type': '[ApplicationGatewayRedirectConfiguration]'},
'web_application_firewall_configuration': {'key': 'properties.webApplicationFirewallConfiguration', 'type': 'ApplicationGatewayWebApplicationFirewallConfiguration'},
'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'},
'enable_http2': {'key': 'properties.enableHttp2', 'type': 'bool'},
'enable_fips': {'key': 'properties.enableFips', 'type': 'bool'},
'autoscale_configuration': {'key': 'properties.autoscaleConfiguration', 'type': 'ApplicationGatewayAutoscaleConfiguration'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'},
'force_firewall_policy_association': {'key': 'properties.forceFirewallPolicyAssociation', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGateway, self).__init__(**kwargs)
self.etag = None
self.zones = kwargs.get('zones', None)
self.identity = kwargs.get('identity', None)
self.sku = kwargs.get('sku', None)
self.ssl_policy = kwargs.get('ssl_policy', None)
self.operational_state = None
self.gateway_ip_configurations = kwargs.get('gateway_ip_configurations', None)
self.authentication_certificates = kwargs.get('authentication_certificates', None)
self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None)
self.ssl_certificates = kwargs.get('ssl_certificates', None)
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.frontend_ports = kwargs.get('frontend_ports', None)
self.probes = kwargs.get('probes', None)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None)
self.http_listeners = kwargs.get('http_listeners', None)
self.url_path_maps = kwargs.get('url_path_maps', None)
self.request_routing_rules = kwargs.get('request_routing_rules', None)
self.rewrite_rule_sets = kwargs.get('rewrite_rule_sets', None)
self.redirect_configurations = kwargs.get('redirect_configurations', None)
self.web_application_firewall_configuration = kwargs.get('web_application_firewall_configuration', None)
self.firewall_policy = kwargs.get('firewall_policy', None)
self.enable_http2 = kwargs.get('enable_http2', None)
self.enable_fips = kwargs.get('enable_fips', None)
self.autoscale_configuration = kwargs.get('autoscale_configuration', None)
self.resource_guid = None
self.provisioning_state = None
self.custom_error_configurations = kwargs.get('custom_error_configurations', None)
self.force_firewall_policy_association = kwargs.get('force_firewall_policy_association', None)
class SubResource(msrest.serialization.Model):
"""Reference to another subresource.
:param id: Resource ID.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubResource, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ApplicationGatewayAuthenticationCertificate(SubResource):
"""Authentication certificates of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the authentication certificate that is unique within an Application
Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param data: Certificate public data.
:type data: str
:ivar provisioning_state: The provisioning state of the authentication certificate resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAuthenticationCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.data = kwargs.get('data', None)
self.provisioning_state = None
class ApplicationGatewayAutoscaleConfiguration(msrest.serialization.Model):
"""Application Gateway autoscale configuration.
All required parameters must be populated in order to send to Azure.
:param min_capacity: Required. Lower bound on number of Application Gateway capacity.
:type min_capacity: int
:param max_capacity: Upper bound on number of Application Gateway capacity.
:type max_capacity: int
"""
_validation = {
'min_capacity': {'required': True, 'minimum': 0},
'max_capacity': {'minimum': 2},
}
_attribute_map = {
'min_capacity': {'key': 'minCapacity', 'type': 'int'},
'max_capacity': {'key': 'maxCapacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAutoscaleConfiguration, self).__init__(**kwargs)
self.min_capacity = kwargs['min_capacity']
self.max_capacity = kwargs.get('max_capacity', None)
class ApplicationGatewayAvailableSslOptions(Resource):
"""Response for ApplicationGatewayAvailableSslOptions API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param predefined_policies: List of available Ssl predefined policy.
:type predefined_policies: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param default_policy: Name of the Ssl predefined policy applied by default to application
gateway. Possible values include: "AppGwSslPolicy20150501", "AppGwSslPolicy20170401",
"AppGwSslPolicy20170401S".
:type default_policy: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslPolicyName
:param available_cipher_suites: List of available Ssl cipher suites.
:type available_cipher_suites: list[str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslCipherSuite]
:param available_protocols: List of available Ssl protocols.
:type available_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslProtocol]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'predefined_policies': {'key': 'properties.predefinedPolicies', 'type': '[SubResource]'},
'default_policy': {'key': 'properties.defaultPolicy', 'type': 'str'},
'available_cipher_suites': {'key': 'properties.availableCipherSuites', 'type': '[str]'},
'available_protocols': {'key': 'properties.availableProtocols', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableSslOptions, self).__init__(**kwargs)
self.predefined_policies = kwargs.get('predefined_policies', None)
self.default_policy = kwargs.get('default_policy', None)
self.available_cipher_suites = kwargs.get('available_cipher_suites', None)
self.available_protocols = kwargs.get('available_protocols', None)
class ApplicationGatewayAvailableSslPredefinedPolicies(msrest.serialization.Model):
"""Response for ApplicationGatewayAvailableSslOptions API service call.
:param value: List of available Ssl predefined policy.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslPredefinedPolicy]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGatewaySslPredefinedPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableSslPredefinedPolicies, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ApplicationGatewayAvailableWafRuleSetsResult(msrest.serialization.Model):
"""Response for ApplicationGatewayAvailableWafRuleSets API service call.
:param value: The list of application gateway rule sets.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallRuleSet]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGatewayFirewallRuleSet]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableWafRuleSetsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ApplicationGatewayBackendAddress(msrest.serialization.Model):
"""Backend address of an application gateway.
:param fqdn: Fully qualified domain name (FQDN).
:type fqdn: str
:param ip_address: IP address.
:type ip_address: str
"""
_attribute_map = {
'fqdn': {'key': 'fqdn', 'type': 'str'},
'ip_address': {'key': 'ipAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendAddress, self).__init__(**kwargs)
self.fqdn = kwargs.get('fqdn', None)
self.ip_address = kwargs.get('ip_address', None)
class ApplicationGatewayBackendAddressPool(SubResource):
"""Backend Address Pool of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the backend address pool that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:ivar backend_ip_configurations: Collection of references to IPs defined in network interfaces.
:vartype backend_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration]
:param backend_addresses: Backend addresses.
:type backend_addresses:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendAddress]
:ivar provisioning_state: The provisioning state of the backend address pool resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'backend_ip_configurations': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'backend_addresses': {'key': 'properties.backendAddresses', 'type': '[ApplicationGatewayBackendAddress]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendAddressPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.backend_ip_configurations = None
self.backend_addresses = kwargs.get('backend_addresses', None)
self.provisioning_state = None
class ApplicationGatewayBackendHealth(msrest.serialization.Model):
"""Response for ApplicationGatewayBackendHealth API service call.
:param backend_address_pools: A list of ApplicationGatewayBackendHealthPool resources.
:type backend_address_pools:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHealthPool]
"""
_attribute_map = {
'backend_address_pools': {'key': 'backendAddressPools', 'type': '[ApplicationGatewayBackendHealthPool]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealth, self).__init__(**kwargs)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
class ApplicationGatewayBackendHealthHttpSettings(msrest.serialization.Model):
"""Application gateway BackendHealthHttp settings.
:param backend_http_settings: Reference to an ApplicationGatewayBackendHttpSettings resource.
:type backend_http_settings:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHttpSettings
:param servers: List of ApplicationGatewayBackendHealthServer resources.
:type servers:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHealthServer]
"""
_attribute_map = {
'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'ApplicationGatewayBackendHttpSettings'},
'servers': {'key': 'servers', 'type': '[ApplicationGatewayBackendHealthServer]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthHttpSettings, self).__init__(**kwargs)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.servers = kwargs.get('servers', None)
class ApplicationGatewayBackendHealthOnDemand(msrest.serialization.Model):
"""Result of on demand test probe.
:param backend_address_pool: Reference to an ApplicationGatewayBackendAddressPool resource.
:type backend_address_pool:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendAddressPool
:param backend_health_http_settings: Application gateway BackendHealthHttp settings.
:type backend_health_http_settings:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHealthHttpSettings
"""
_attribute_map = {
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'},
'backend_health_http_settings': {'key': 'backendHealthHttpSettings', 'type': 'ApplicationGatewayBackendHealthHttpSettings'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthOnDemand, self).__init__(**kwargs)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_health_http_settings = kwargs.get('backend_health_http_settings', None)
class ApplicationGatewayBackendHealthPool(msrest.serialization.Model):
"""Application gateway BackendHealth pool.
:param backend_address_pool: Reference to an ApplicationGatewayBackendAddressPool resource.
:type backend_address_pool:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendAddressPool
:param backend_http_settings_collection: List of ApplicationGatewayBackendHealthHttpSettings
resources.
:type backend_http_settings_collection:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHealthHttpSettings]
"""
_attribute_map = {
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'},
'backend_http_settings_collection': {'key': 'backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHealthHttpSettings]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthPool, self).__init__(**kwargs)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None)
class ApplicationGatewayBackendHealthServer(msrest.serialization.Model):
"""Application gateway backendhealth http settings.
:param address: IP address or FQDN of backend server.
:type address: str
:param ip_configuration: Reference to IP configuration of backend server.
:type ip_configuration: ~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration
:param health: Health of backend server. Possible values include: "Unknown", "Up", "Down",
"Partial", "Draining".
:type health: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendHealthServerHealth
:param health_probe_log: Health Probe Log.
:type health_probe_log: str
"""
_attribute_map = {
'address': {'key': 'address', 'type': 'str'},
'ip_configuration': {'key': 'ipConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'health': {'key': 'health', 'type': 'str'},
'health_probe_log': {'key': 'healthProbeLog', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthServer, self).__init__(**kwargs)
self.address = kwargs.get('address', None)
self.ip_configuration = kwargs.get('ip_configuration', None)
self.health = kwargs.get('health', None)
self.health_probe_log = kwargs.get('health_probe_log', None)
class ApplicationGatewayBackendHttpSettings(SubResource):
"""Backend address pool settings of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the backend http settings that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param port: The destination port on the backend.
:type port: int
:param protocol: The protocol used to communicate with the backend. Possible values include:
"Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProtocol
:param cookie_based_affinity: Cookie based affinity. Possible values include: "Enabled",
"Disabled".
:type cookie_based_affinity: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayCookieBasedAffinity
:param request_timeout: Request timeout in seconds. Application Gateway will fail the request
if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400
seconds.
:type request_timeout: int
:param probe: Probe resource of an application gateway.
:type probe: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param authentication_certificates: Array of references to application gateway authentication
certificates.
:type authentication_certificates: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param trusted_root_certificates: Array of references to application gateway trusted root
certificates.
:type trusted_root_certificates: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param connection_draining: Connection draining of the backend http settings resource.
:type connection_draining:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayConnectionDraining
:param host_name: Host header to be sent to the backend servers.
:type host_name: str
:param pick_host_name_from_backend_address: Whether to pick host header should be picked from
the host name of the backend server. Default value is false.
:type pick_host_name_from_backend_address: bool
:param affinity_cookie_name: Cookie name to use for the affinity cookie.
:type affinity_cookie_name: str
:param probe_enabled: Whether the probe is enabled. Default value is false.
:type probe_enabled: bool
:param path: Path which should be used as a prefix for all HTTP requests. Null means no path
will be prefixed. Default value is null.
:type path: str
:ivar provisioning_state: The provisioning state of the backend HTTP settings resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'cookie_based_affinity': {'key': 'properties.cookieBasedAffinity', 'type': 'str'},
'request_timeout': {'key': 'properties.requestTimeout', 'type': 'int'},
'probe': {'key': 'properties.probe', 'type': 'SubResource'},
'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[SubResource]'},
'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[SubResource]'},
'connection_draining': {'key': 'properties.connectionDraining', 'type': 'ApplicationGatewayConnectionDraining'},
'host_name': {'key': 'properties.hostName', 'type': 'str'},
'pick_host_name_from_backend_address': {'key': 'properties.pickHostNameFromBackendAddress', 'type': 'bool'},
'affinity_cookie_name': {'key': 'properties.affinityCookieName', 'type': 'str'},
'probe_enabled': {'key': 'properties.probeEnabled', 'type': 'bool'},
'path': {'key': 'properties.path', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHttpSettings, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.port = kwargs.get('port', None)
self.protocol = kwargs.get('protocol', None)
self.cookie_based_affinity = kwargs.get('cookie_based_affinity', None)
self.request_timeout = kwargs.get('request_timeout', None)
self.probe = kwargs.get('probe', None)
self.authentication_certificates = kwargs.get('authentication_certificates', None)
self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None)
self.connection_draining = kwargs.get('connection_draining', None)
self.host_name = kwargs.get('host_name', None)
self.pick_host_name_from_backend_address = kwargs.get('pick_host_name_from_backend_address', None)
self.affinity_cookie_name = kwargs.get('affinity_cookie_name', None)
self.probe_enabled = kwargs.get('probe_enabled', None)
self.path = kwargs.get('path', None)
self.provisioning_state = None
class ApplicationGatewayConnectionDraining(msrest.serialization.Model):
"""Connection draining allows open connections to a backend server to be active for a specified time after the backend server got removed from the configuration.
All required parameters must be populated in order to send to Azure.
:param enabled: Required. Whether connection draining is enabled or not.
:type enabled: bool
:param drain_timeout_in_sec: Required. The number of seconds connection draining is active.
Acceptable values are from 1 second to 3600 seconds.
:type drain_timeout_in_sec: int
"""
_validation = {
'enabled': {'required': True},
'drain_timeout_in_sec': {'required': True, 'maximum': 3600, 'minimum': 1},
}
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'drain_timeout_in_sec': {'key': 'drainTimeoutInSec', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayConnectionDraining, self).__init__(**kwargs)
self.enabled = kwargs['enabled']
self.drain_timeout_in_sec = kwargs['drain_timeout_in_sec']
class ApplicationGatewayCustomError(msrest.serialization.Model):
"""Customer error of an application gateway.
:param status_code: Status code of the application gateway customer error. Possible values
include: "HttpStatus403", "HttpStatus502".
:type status_code: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayCustomErrorStatusCode
:param custom_error_page_url: Error page URL of the application gateway customer error.
:type custom_error_page_url: str
"""
_attribute_map = {
'status_code': {'key': 'statusCode', 'type': 'str'},
'custom_error_page_url': {'key': 'customErrorPageUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayCustomError, self).__init__(**kwargs)
self.status_code = kwargs.get('status_code', None)
self.custom_error_page_url = kwargs.get('custom_error_page_url', None)
class ApplicationGatewayFirewallDisabledRuleGroup(msrest.serialization.Model):
"""Allows to disable rules within a rule group or an entire rule group.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The name of the rule group that will be disabled.
:type rule_group_name: str
:param rules: The list of rules that will be disabled. If null, all rules of the rule group
will be disabled.
:type rules: list[int]
"""
_validation = {
'rule_group_name': {'required': True},
}
_attribute_map = {
'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'},
'rules': {'key': 'rules', 'type': '[int]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallDisabledRuleGroup, self).__init__(**kwargs)
self.rule_group_name = kwargs['rule_group_name']
self.rules = kwargs.get('rules', None)
class ApplicationGatewayFirewallExclusion(msrest.serialization.Model):
"""Allow to exclude some variable satisfy the condition for the WAF check.
All required parameters must be populated in order to send to Azure.
:param match_variable: Required. The variable to be excluded.
:type match_variable: str
:param selector_match_operator: Required. When matchVariable is a collection, operate on the
selector to specify which elements in the collection this exclusion applies to.
:type selector_match_operator: str
:param selector: Required. When matchVariable is a collection, operator used to specify which
elements in the collection this exclusion applies to.
:type selector: str
"""
_validation = {
'match_variable': {'required': True},
'selector_match_operator': {'required': True},
'selector': {'required': True},
}
_attribute_map = {
'match_variable': {'key': 'matchVariable', 'type': 'str'},
'selector_match_operator': {'key': 'selectorMatchOperator', 'type': 'str'},
'selector': {'key': 'selector', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallExclusion, self).__init__(**kwargs)
self.match_variable = kwargs['match_variable']
self.selector_match_operator = kwargs['selector_match_operator']
self.selector = kwargs['selector']
class ApplicationGatewayFirewallRule(msrest.serialization.Model):
"""A web application firewall rule.
All required parameters must be populated in order to send to Azure.
:param rule_id: Required. The identifier of the web application firewall rule.
:type rule_id: int
:param description: The description of the web application firewall rule.
:type description: str
"""
_validation = {
'rule_id': {'required': True},
}
_attribute_map = {
'rule_id': {'key': 'ruleId', 'type': 'int'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRule, self).__init__(**kwargs)
self.rule_id = kwargs['rule_id']
self.description = kwargs.get('description', None)
class ApplicationGatewayFirewallRuleGroup(msrest.serialization.Model):
"""A web application firewall rule group.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The name of the web application firewall rule group.
:type rule_group_name: str
:param description: The description of the web application firewall rule group.
:type description: str
:param rules: Required. The rules of the web application firewall rule group.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallRule]
"""
_validation = {
'rule_group_name': {'required': True},
'rules': {'required': True},
}
_attribute_map = {
'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rules': {'key': 'rules', 'type': '[ApplicationGatewayFirewallRule]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRuleGroup, self).__init__(**kwargs)
self.rule_group_name = kwargs['rule_group_name']
self.description = kwargs.get('description', None)
self.rules = kwargs['rules']
class ApplicationGatewayFirewallRuleSet(Resource):
"""A web application firewall rule set.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar provisioning_state: The provisioning state of the web application firewall rule set.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param rule_set_type: The type of the web application firewall rule set.
:type rule_set_type: str
:param rule_set_version: The version of the web application firewall rule set type.
:type rule_set_version: str
:param rule_groups: The rule groups of the web application firewall rule set.
:type rule_groups:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallRuleGroup]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'rule_set_type': {'key': 'properties.ruleSetType', 'type': 'str'},
'rule_set_version': {'key': 'properties.ruleSetVersion', 'type': 'str'},
'rule_groups': {'key': 'properties.ruleGroups', 'type': '[ApplicationGatewayFirewallRuleGroup]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRuleSet, self).__init__(**kwargs)
self.provisioning_state = None
self.rule_set_type = kwargs.get('rule_set_type', None)
self.rule_set_version = kwargs.get('rule_set_version', None)
self.rule_groups = kwargs.get('rule_groups', None)
class ApplicationGatewayFrontendIPConfiguration(SubResource):
"""Frontend IP configuration of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the frontend IP configuration that is unique within an Application
Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param private_ip_address: PrivateIPAddress of the network interface IP Configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param subnet: Reference to the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param public_ip_address: Reference to the PublicIP resource.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the frontend IP configuration resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFrontendIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
class ApplicationGatewayFrontendPort(SubResource):
"""Frontend port of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the frontend port that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param port: Frontend port.
:type port: int
:ivar provisioning_state: The provisioning state of the frontend port resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFrontendPort, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.port = kwargs.get('port', None)
self.provisioning_state = None
class ApplicationGatewayHeaderConfiguration(msrest.serialization.Model):
"""Header configuration of the Actions set in Application Gateway.
:param header_name: Header name of the header configuration.
:type header_name: str
:param header_value: Header value of the header configuration.
:type header_value: str
"""
_attribute_map = {
'header_name': {'key': 'headerName', 'type': 'str'},
'header_value': {'key': 'headerValue', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayHeaderConfiguration, self).__init__(**kwargs)
self.header_name = kwargs.get('header_name', None)
self.header_value = kwargs.get('header_value', None)
class ApplicationGatewayHttpListener(SubResource):
"""Http listener of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the HTTP listener that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param frontend_ip_configuration: Frontend IP configuration resource of an application gateway.
:type frontend_ip_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param frontend_port: Frontend port resource of an application gateway.
:type frontend_port: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param protocol: Protocol of the HTTP listener. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProtocol
:param host_name: Host name of HTTP listener.
:type host_name: str
:param ssl_certificate: SSL certificate resource of an application gateway.
:type ssl_certificate: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param require_server_name_indication: Applicable only if protocol is https. Enables SNI for
multi-hosting.
:type require_server_name_indication: bool
:ivar provisioning_state: The provisioning state of the HTTP listener resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param custom_error_configurations: Custom error configurations of the HTTP listener.
:type custom_error_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayCustomError]
:param firewall_policy: Reference to the FirewallPolicy resource.
:type firewall_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param host_names: List of Host names for HTTP Listener that allows special wildcard characters
as well.
:type host_names: list[str]
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'host_name': {'key': 'properties.hostName', 'type': 'str'},
'ssl_certificate': {'key': 'properties.sslCertificate', 'type': 'SubResource'},
'require_server_name_indication': {'key': 'properties.requireServerNameIndication', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'},
'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'},
'host_names': {'key': 'properties.hostNames', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayHttpListener, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.protocol = kwargs.get('protocol', None)
self.host_name = kwargs.get('host_name', None)
self.ssl_certificate = kwargs.get('ssl_certificate', None)
self.require_server_name_indication = kwargs.get('require_server_name_indication', None)
self.provisioning_state = None
self.custom_error_configurations = kwargs.get('custom_error_configurations', None)
self.firewall_policy = kwargs.get('firewall_policy', None)
self.host_names = kwargs.get('host_names', None)
class ApplicationGatewayIPConfiguration(SubResource):
"""IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the IP configuration that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param subnet: Reference to the subnet resource. A subnet from where application gateway gets
its private address.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the application gateway IP configuration
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.subnet = kwargs.get('subnet', None)
self.provisioning_state = None
class ApplicationGatewayListResult(msrest.serialization.Model):
"""Response for ListApplicationGateways API service call.
:param value: List of an application gateways in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGateway]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ApplicationGatewayOnDemandProbe(msrest.serialization.Model):
"""Details of on demand test probe request.
:param protocol: The protocol used for the probe. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProtocol
:param host: Host name to send the probe to.
:type host: str
:param path: Relative path of probe. Valid path starts from '/'. Probe is sent to
:code:`<Protocol>`://:code:`<host>`::code:`<port>`:code:`<path>`.
:type path: str
:param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not
received with this timeout period. Acceptable values are from 1 second to 86400 seconds.
:type timeout: int
:param pick_host_name_from_backend_http_settings: Whether the host header should be picked from
the backend http settings. Default value is false.
:type pick_host_name_from_backend_http_settings: bool
:param match: Criterion for classifying a healthy probe response.
:type match: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProbeHealthResponseMatch
:param backend_address_pool: Reference to backend pool of application gateway to which probe
request will be sent.
:type backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param backend_http_settings: Reference to backend http setting of application gateway to be
used for test probe.
:type backend_http_settings: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'host': {'key': 'host', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'},
'timeout': {'key': 'timeout', 'type': 'int'},
'pick_host_name_from_backend_http_settings': {'key': 'pickHostNameFromBackendHttpSettings', 'type': 'bool'},
'match': {'key': 'match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'},
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayOnDemandProbe, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', None)
self.host = kwargs.get('host', None)
self.path = kwargs.get('path', None)
self.timeout = kwargs.get('timeout', None)
self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None)
self.match = kwargs.get('match', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
class ApplicationGatewayPathRule(SubResource):
"""Path rule of URL path map of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the path rule that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param paths: Path rules of URL path map.
:type paths: list[str]
:param backend_address_pool: Backend address pool resource of URL path map path rule.
:type backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param backend_http_settings: Backend http settings resource of URL path map path rule.
:type backend_http_settings: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param redirect_configuration: Redirect configuration resource of URL path map path rule.
:type redirect_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param rewrite_rule_set: Rewrite rule set resource of URL path map path rule.
:type rewrite_rule_set: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the path rule resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param firewall_policy: Reference to the FirewallPolicy resource.
:type firewall_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'paths': {'key': 'properties.paths', 'type': '[str]'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'},
'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'},
'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayPathRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.paths = kwargs.get('paths', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.redirect_configuration = kwargs.get('redirect_configuration', None)
self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None)
self.provisioning_state = None
self.firewall_policy = kwargs.get('firewall_policy', None)
class ApplicationGatewayProbe(SubResource):
"""Probe of the application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the probe that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param protocol: The protocol used for the probe. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProtocol
:param host: Host name to send the probe to.
:type host: str
:param path: Relative path of probe. Valid path starts from '/'. Probe is sent to
:code:`<Protocol>`://:code:`<host>`::code:`<port>`:code:`<path>`.
:type path: str
:param interval: The probing interval in seconds. This is the time interval between two
consecutive probes. Acceptable values are from 1 second to 86400 seconds.
:type interval: int
:param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not
received with this timeout period. Acceptable values are from 1 second to 86400 seconds.
:type timeout: int
:param unhealthy_threshold: The probe retry count. Backend server is marked down after
consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second
to 20.
:type unhealthy_threshold: int
:param pick_host_name_from_backend_http_settings: Whether the host header should be picked from
the backend http settings. Default value is false.
:type pick_host_name_from_backend_http_settings: bool
:param min_servers: Minimum number of servers that are always marked healthy. Default value is
0.
:type min_servers: int
:param match: Criterion for classifying a healthy probe response.
:type match: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayProbeHealthResponseMatch
:ivar provisioning_state: The provisioning state of the probe resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param port: Custom port which will be used for probing the backend servers. The valid value
ranges from 1 to 65535. In case not set, port from http settings will be used. This property is
valid for Standard_v2 and WAF_v2 only.
:type port: int
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
'port': {'maximum': 65535, 'minimum': 1},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'host': {'key': 'properties.host', 'type': 'str'},
'path': {'key': 'properties.path', 'type': 'str'},
'interval': {'key': 'properties.interval', 'type': 'int'},
'timeout': {'key': 'properties.timeout', 'type': 'int'},
'unhealthy_threshold': {'key': 'properties.unhealthyThreshold', 'type': 'int'},
'pick_host_name_from_backend_http_settings': {'key': 'properties.pickHostNameFromBackendHttpSettings', 'type': 'bool'},
'min_servers': {'key': 'properties.minServers', 'type': 'int'},
'match': {'key': 'properties.match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayProbe, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.protocol = kwargs.get('protocol', None)
self.host = kwargs.get('host', None)
self.path = kwargs.get('path', None)
self.interval = kwargs.get('interval', None)
self.timeout = kwargs.get('timeout', None)
self.unhealthy_threshold = kwargs.get('unhealthy_threshold', None)
self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None)
self.min_servers = kwargs.get('min_servers', None)
self.match = kwargs.get('match', None)
self.provisioning_state = None
self.port = kwargs.get('port', None)
class ApplicationGatewayProbeHealthResponseMatch(msrest.serialization.Model):
"""Application gateway probe health response match.
:param body: Body that must be contained in the health response. Default value is empty.
:type body: str
:param status_codes: Allowed ranges of healthy status codes. Default range of healthy status
codes is 200-399.
:type status_codes: list[str]
"""
_attribute_map = {
'body': {'key': 'body', 'type': 'str'},
'status_codes': {'key': 'statusCodes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayProbeHealthResponseMatch, self).__init__(**kwargs)
self.body = kwargs.get('body', None)
self.status_codes = kwargs.get('status_codes', None)
class ApplicationGatewayRedirectConfiguration(SubResource):
"""Redirect configuration of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the redirect configuration that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param redirect_type: HTTP redirection type. Possible values include: "Permanent", "Found",
"SeeOther", "Temporary".
:type redirect_type: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRedirectType
:param target_listener: Reference to a listener to redirect the request to.
:type target_listener: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param target_url: Url to redirect the request to.
:type target_url: str
:param include_path: Include path in the redirected url.
:type include_path: bool
:param include_query_string: Include query string in the redirected url.
:type include_query_string: bool
:param request_routing_rules: Request routing specifying redirect configuration.
:type request_routing_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param url_path_maps: Url path maps specifying default redirect configuration.
:type url_path_maps: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param path_rules: Path rules specifying redirect configuration.
:type path_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'redirect_type': {'key': 'properties.redirectType', 'type': 'str'},
'target_listener': {'key': 'properties.targetListener', 'type': 'SubResource'},
'target_url': {'key': 'properties.targetUrl', 'type': 'str'},
'include_path': {'key': 'properties.includePath', 'type': 'bool'},
'include_query_string': {'key': 'properties.includeQueryString', 'type': 'bool'},
'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[SubResource]'},
'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[SubResource]'},
'path_rules': {'key': 'properties.pathRules', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRedirectConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.redirect_type = kwargs.get('redirect_type', None)
self.target_listener = kwargs.get('target_listener', None)
self.target_url = kwargs.get('target_url', None)
self.include_path = kwargs.get('include_path', None)
self.include_query_string = kwargs.get('include_query_string', None)
self.request_routing_rules = kwargs.get('request_routing_rules', None)
self.url_path_maps = kwargs.get('url_path_maps', None)
self.path_rules = kwargs.get('path_rules', None)
class ApplicationGatewayRequestRoutingRule(SubResource):
"""Request routing rule of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the request routing rule that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param rule_type: Rule type. Possible values include: "Basic", "PathBasedRouting".
:type rule_type: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRequestRoutingRuleType
:param priority: Priority of the request routing rule.
:type priority: int
:param backend_address_pool: Backend address pool resource of the application gateway.
:type backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param backend_http_settings: Backend http settings resource of the application gateway.
:type backend_http_settings: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param http_listener: Http listener resource of the application gateway.
:type http_listener: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param url_path_map: URL path map resource of the application gateway.
:type url_path_map: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param rewrite_rule_set: Rewrite Rule Set resource in Basic rule of the application gateway.
:type rewrite_rule_set: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param redirect_configuration: Redirect configuration resource of the application gateway.
:type redirect_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the request routing rule resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'priority': {'maximum': 20000, 'minimum': 1},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'rule_type': {'key': 'properties.ruleType', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'},
'http_listener': {'key': 'properties.httpListener', 'type': 'SubResource'},
'url_path_map': {'key': 'properties.urlPathMap', 'type': 'SubResource'},
'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'},
'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRequestRoutingRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.rule_type = kwargs.get('rule_type', None)
self.priority = kwargs.get('priority', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.http_listener = kwargs.get('http_listener', None)
self.url_path_map = kwargs.get('url_path_map', None)
self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None)
self.redirect_configuration = kwargs.get('redirect_configuration', None)
self.provisioning_state = None
class ApplicationGatewayRewriteRule(msrest.serialization.Model):
"""Rewrite rule of an application gateway.
:param name: Name of the rewrite rule that is unique within an Application Gateway.
:type name: str
:param rule_sequence: Rule Sequence of the rewrite rule that determines the order of execution
of a particular rule in a RewriteRuleSet.
:type rule_sequence: int
:param conditions: Conditions based on which the action set execution will be evaluated.
:type conditions:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRewriteRuleCondition]
:param action_set: Set of actions to be done as part of the rewrite Rule.
:type action_set: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRewriteRuleActionSet
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'rule_sequence': {'key': 'ruleSequence', 'type': 'int'},
'conditions': {'key': 'conditions', 'type': '[ApplicationGatewayRewriteRuleCondition]'},
'action_set': {'key': 'actionSet', 'type': 'ApplicationGatewayRewriteRuleActionSet'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.rule_sequence = kwargs.get('rule_sequence', None)
self.conditions = kwargs.get('conditions', None)
self.action_set = kwargs.get('action_set', None)
class ApplicationGatewayRewriteRuleActionSet(msrest.serialization.Model):
"""Set of actions in the Rewrite Rule in Application Gateway.
:param request_header_configurations: Request Header Actions in the Action Set.
:type request_header_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayHeaderConfiguration]
:param response_header_configurations: Response Header Actions in the Action Set.
:type response_header_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayHeaderConfiguration]
:param url_configuration: Url Configuration Action in the Action Set.
:type url_configuration:
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayUrlConfiguration
"""
_attribute_map = {
'request_header_configurations': {'key': 'requestHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'},
'response_header_configurations': {'key': 'responseHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'},
'url_configuration': {'key': 'urlConfiguration', 'type': 'ApplicationGatewayUrlConfiguration'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleActionSet, self).__init__(**kwargs)
self.request_header_configurations = kwargs.get('request_header_configurations', None)
self.response_header_configurations = kwargs.get('response_header_configurations', None)
self.url_configuration = kwargs.get('url_configuration', None)
class ApplicationGatewayRewriteRuleCondition(msrest.serialization.Model):
"""Set of conditions in the Rewrite Rule in Application Gateway.
:param variable: The condition parameter of the RewriteRuleCondition.
:type variable: str
:param pattern: The pattern, either fixed string or regular expression, that evaluates the
truthfulness of the condition.
:type pattern: str
:param ignore_case: Setting this parameter to truth value with force the pattern to do a case
in-sensitive comparison.
:type ignore_case: bool
:param negate: Setting this value as truth will force to check the negation of the condition
given by the user.
:type negate: bool
"""
_attribute_map = {
'variable': {'key': 'variable', 'type': 'str'},
'pattern': {'key': 'pattern', 'type': 'str'},
'ignore_case': {'key': 'ignoreCase', 'type': 'bool'},
'negate': {'key': 'negate', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleCondition, self).__init__(**kwargs)
self.variable = kwargs.get('variable', None)
self.pattern = kwargs.get('pattern', None)
self.ignore_case = kwargs.get('ignore_case', None)
self.negate = kwargs.get('negate', None)
class ApplicationGatewayRewriteRuleSet(SubResource):
"""Rewrite rule set of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the rewrite rule set that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rewrite_rules: Rewrite rules in the rewrite rule set.
:type rewrite_rules: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayRewriteRule]
:ivar provisioning_state: The provisioning state of the rewrite rule set resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'rewrite_rules': {'key': 'properties.rewriteRules', 'type': '[ApplicationGatewayRewriteRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleSet, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.rewrite_rules = kwargs.get('rewrite_rules', None)
self.provisioning_state = None
class ApplicationGatewaySku(msrest.serialization.Model):
"""SKU of an application gateway.
:param name: Name of an application gateway SKU. Possible values include: "Standard_Small",
"Standard_Medium", "Standard_Large", "WAF_Medium", "WAF_Large", "Standard_v2", "WAF_v2".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySkuName
:param tier: Tier of an application gateway. Possible values include: "Standard", "WAF",
"Standard_v2", "WAF_v2".
:type tier: str or ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayTier
:param capacity: Capacity (instance count) of an application gateway.
:type capacity: int
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'capacity': {'key': 'capacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.capacity = kwargs.get('capacity', None)
class ApplicationGatewaySslCertificate(SubResource):
"""SSL certificates of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the SSL certificate that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param data: Base-64 encoded pfx certificate. Only applicable in PUT Request.
:type data: str
:param password: Password for the pfx file specified in data. Only applicable in PUT request.
:type password: str
:ivar public_cert_data: Base-64 encoded Public cert data corresponding to pfx specified in
data. Only applicable in GET request.
:vartype public_cert_data: str
:param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or
'Certificate' object stored in KeyVault.
:type key_vault_secret_id: str
:ivar provisioning_state: The provisioning state of the SSL certificate resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'public_cert_data': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'password': {'key': 'properties.password', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.data = kwargs.get('data', None)
self.password = kwargs.get('password', None)
self.public_cert_data = None
self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None)
self.provisioning_state = None
class ApplicationGatewaySslPolicy(msrest.serialization.Model):
"""Application Gateway Ssl policy.
:param disabled_ssl_protocols: Ssl protocols to be disabled on application gateway.
:type disabled_ssl_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslProtocol]
:param policy_type: Type of Ssl Policy. Possible values include: "Predefined", "Custom".
:type policy_type: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslPolicyType
:param policy_name: Name of Ssl predefined policy. Possible values include:
"AppGwSslPolicy20150501", "AppGwSslPolicy20170401", "AppGwSslPolicy20170401S".
:type policy_name: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslPolicyName
:param cipher_suites: Ssl cipher suites to be enabled in the specified order to application
gateway.
:type cipher_suites: list[str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslCipherSuite]
:param min_protocol_version: Minimum version of Ssl protocol to be supported on application
gateway. Possible values include: "TLSv1_0", "TLSv1_1", "TLSv1_2".
:type min_protocol_version: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslProtocol
"""
_attribute_map = {
'disabled_ssl_protocols': {'key': 'disabledSslProtocols', 'type': '[str]'},
'policy_type': {'key': 'policyType', 'type': 'str'},
'policy_name': {'key': 'policyName', 'type': 'str'},
'cipher_suites': {'key': 'cipherSuites', 'type': '[str]'},
'min_protocol_version': {'key': 'minProtocolVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslPolicy, self).__init__(**kwargs)
self.disabled_ssl_protocols = kwargs.get('disabled_ssl_protocols', None)
self.policy_type = kwargs.get('policy_type', None)
self.policy_name = kwargs.get('policy_name', None)
self.cipher_suites = kwargs.get('cipher_suites', None)
self.min_protocol_version = kwargs.get('min_protocol_version', None)
class ApplicationGatewaySslPredefinedPolicy(SubResource):
"""An Ssl predefined policy.
:param id: Resource ID.
:type id: str
:param name: Name of the Ssl predefined policy.
:type name: str
:param cipher_suites: Ssl cipher suites to be enabled in the specified order for application
gateway.
:type cipher_suites: list[str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslCipherSuite]
:param min_protocol_version: Minimum version of Ssl protocol to be supported on application
gateway. Possible values include: "TLSv1_0", "TLSv1_1", "TLSv1_2".
:type min_protocol_version: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySslProtocol
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'},
'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.cipher_suites = kwargs.get('cipher_suites', None)
self.min_protocol_version = kwargs.get('min_protocol_version', None)
class ApplicationGatewayTrustedRootCertificate(SubResource):
"""Trusted Root certificates of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the trusted root certificate that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param data: Certificate public data.
:type data: str
:param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or
'Certificate' object stored in KeyVault.
:type key_vault_secret_id: str
:ivar provisioning_state: The provisioning state of the trusted root certificate resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayTrustedRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.data = kwargs.get('data', None)
self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None)
self.provisioning_state = None
class ApplicationGatewayUrlConfiguration(msrest.serialization.Model):
"""Url configuration of the Actions set in Application Gateway.
:param modified_path: Url path which user has provided for url rewrite. Null means no path will
be updated. Default value is null.
:type modified_path: str
:param modified_query_string: Query string which user has provided for url rewrite. Null means
no query string will be updated. Default value is null.
:type modified_query_string: str
:param reroute: If set as true, it will re-evaluate the url path map provided in path based
request routing rules using modified path. Default value is false.
:type reroute: bool
"""
_attribute_map = {
'modified_path': {'key': 'modifiedPath', 'type': 'str'},
'modified_query_string': {'key': 'modifiedQueryString', 'type': 'str'},
'reroute': {'key': 'reroute', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayUrlConfiguration, self).__init__(**kwargs)
self.modified_path = kwargs.get('modified_path', None)
self.modified_query_string = kwargs.get('modified_query_string', None)
self.reroute = kwargs.get('reroute', None)
class ApplicationGatewayUrlPathMap(SubResource):
"""UrlPathMaps give a url path to the backend mapping information for PathBasedRouting.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the URL path map that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param default_backend_address_pool: Default backend address pool resource of URL path map.
:type default_backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param default_backend_http_settings: Default backend http settings resource of URL path map.
:type default_backend_http_settings: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param default_rewrite_rule_set: Default Rewrite rule set resource of URL path map.
:type default_rewrite_rule_set: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param default_redirect_configuration: Default redirect configuration resource of URL path map.
:type default_redirect_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param path_rules: Path rule of URL path map resource.
:type path_rules: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayPathRule]
:ivar provisioning_state: The provisioning state of the URL path map resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'},
'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'},
'default_rewrite_rule_set': {'key': 'properties.defaultRewriteRuleSet', 'type': 'SubResource'},
'default_redirect_configuration': {'key': 'properties.defaultRedirectConfiguration', 'type': 'SubResource'},
'path_rules': {'key': 'properties.pathRules', 'type': '[ApplicationGatewayPathRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayUrlPathMap, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.default_backend_address_pool = kwargs.get('default_backend_address_pool', None)
self.default_backend_http_settings = kwargs.get('default_backend_http_settings', None)
self.default_rewrite_rule_set = kwargs.get('default_rewrite_rule_set', None)
self.default_redirect_configuration = kwargs.get('default_redirect_configuration', None)
self.path_rules = kwargs.get('path_rules', None)
self.provisioning_state = None
class ApplicationGatewayWebApplicationFirewallConfiguration(msrest.serialization.Model):
"""Application gateway web application firewall configuration.
All required parameters must be populated in order to send to Azure.
:param enabled: Required. Whether the web application firewall is enabled or not.
:type enabled: bool
:param firewall_mode: Required. Web application firewall mode. Possible values include:
"Detection", "Prevention".
:type firewall_mode: str or
~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallMode
:param rule_set_type: Required. The type of the web application firewall rule set. Possible
values are: 'OWASP'.
:type rule_set_type: str
:param rule_set_version: Required. The version of the rule set type.
:type rule_set_version: str
:param disabled_rule_groups: The disabled rule groups.
:type disabled_rule_groups:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallDisabledRuleGroup]
:param request_body_check: Whether allow WAF to check request Body.
:type request_body_check: bool
:param max_request_body_size: Maximum request body size for WAF.
:type max_request_body_size: int
:param max_request_body_size_in_kb: Maximum request body size in Kb for WAF.
:type max_request_body_size_in_kb: int
:param file_upload_limit_in_mb: Maximum file upload size in Mb for WAF.
:type file_upload_limit_in_mb: int
:param exclusions: The exclusion list.
:type exclusions:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayFirewallExclusion]
"""
_validation = {
'enabled': {'required': True},
'firewall_mode': {'required': True},
'rule_set_type': {'required': True},
'rule_set_version': {'required': True},
'max_request_body_size': {'maximum': 128, 'minimum': 8},
'max_request_body_size_in_kb': {'maximum': 128, 'minimum': 8},
'file_upload_limit_in_mb': {'minimum': 0},
}
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'firewall_mode': {'key': 'firewallMode', 'type': 'str'},
'rule_set_type': {'key': 'ruleSetType', 'type': 'str'},
'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'},
'disabled_rule_groups': {'key': 'disabledRuleGroups', 'type': '[ApplicationGatewayFirewallDisabledRuleGroup]'},
'request_body_check': {'key': 'requestBodyCheck', 'type': 'bool'},
'max_request_body_size': {'key': 'maxRequestBodySize', 'type': 'int'},
'max_request_body_size_in_kb': {'key': 'maxRequestBodySizeInKb', 'type': 'int'},
'file_upload_limit_in_mb': {'key': 'fileUploadLimitInMb', 'type': 'int'},
'exclusions': {'key': 'exclusions', 'type': '[ApplicationGatewayFirewallExclusion]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs)
self.enabled = kwargs['enabled']
self.firewall_mode = kwargs['firewall_mode']
self.rule_set_type = kwargs['rule_set_type']
self.rule_set_version = kwargs['rule_set_version']
self.disabled_rule_groups = kwargs.get('disabled_rule_groups', None)
self.request_body_check = kwargs.get('request_body_check', None)
self.max_request_body_size = kwargs.get('max_request_body_size', None)
self.max_request_body_size_in_kb = kwargs.get('max_request_body_size_in_kb', None)
self.file_upload_limit_in_mb = kwargs.get('file_upload_limit_in_mb', None)
self.exclusions = kwargs.get('exclusions', None)
class FirewallPolicyRuleCondition(msrest.serialization.Model):
"""Properties of a rule.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: ApplicationRuleCondition, NatRuleCondition, NetworkRuleCondition.
All required parameters must be populated in order to send to Azure.
:param name: Name of the rule condition.
:type name: str
:param description: Description of the rule condition.
:type description: str
:param rule_condition_type: Required. Rule Condition Type.Constant filled by server. Possible
values include: "ApplicationRuleCondition", "NetworkRuleCondition", "NatRuleCondition".
:type rule_condition_type: str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionType
"""
_validation = {
'rule_condition_type': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rule_condition_type': {'key': 'ruleConditionType', 'type': 'str'},
}
_subtype_map = {
'rule_condition_type': {'ApplicationRuleCondition': 'ApplicationRuleCondition', 'NatRuleCondition': 'NatRuleCondition', 'NetworkRuleCondition': 'NetworkRuleCondition'}
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyRuleCondition, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.rule_condition_type = None # type: Optional[str]
class ApplicationRuleCondition(FirewallPolicyRuleCondition):
"""Rule condition of type application.
All required parameters must be populated in order to send to Azure.
:param name: Name of the rule condition.
:type name: str
:param description: Description of the rule condition.
:type description: str
:param rule_condition_type: Required. Rule Condition Type.Constant filled by server. Possible
values include: "ApplicationRuleCondition", "NetworkRuleCondition", "NatRuleCondition".
:type rule_condition_type: str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionType
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses or Service Tags.
:type destination_addresses: list[str]
:param protocols: Array of Application Protocols.
:type protocols:
list[~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionApplicationProtocol]
:param target_fqdns: List of FQDNs for this rule condition.
:type target_fqdns: list[str]
:param fqdn_tags: List of FQDN Tags for this rule condition.
:type fqdn_tags: list[str]
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
"""
_validation = {
'rule_condition_type': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rule_condition_type': {'key': 'ruleConditionType', 'type': 'str'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'protocols': {'key': 'protocols', 'type': '[FirewallPolicyRuleConditionApplicationProtocol]'},
'target_fqdns': {'key': 'targetFqdns', 'type': '[str]'},
'fqdn_tags': {'key': 'fqdnTags', 'type': '[str]'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationRuleCondition, self).__init__(**kwargs)
self.rule_condition_type = 'ApplicationRuleCondition' # type: str
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.protocols = kwargs.get('protocols', None)
self.target_fqdns = kwargs.get('target_fqdns', None)
self.fqdn_tags = kwargs.get('fqdn_tags', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
class ApplicationSecurityGroup(Resource):
"""An application security group in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the application security group resource. It
uniquely identifies a resource, even if the user changes its name or migrate the resource
across subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the application security group resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationSecurityGroup, self).__init__(**kwargs)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
class ApplicationSecurityGroupListResult(msrest.serialization.Model):
"""A list of application security groups.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of application security groups.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ApplicationSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AuthorizationListResult(msrest.serialization.Model):
"""Response for ListAuthorizations API service call retrieves all authorizations that belongs to an ExpressRouteCircuit.
:param value: The authorizations in an ExpressRoute Circuit.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitAuthorization]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitAuthorization]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AuthorizationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AutoApprovedPrivateLinkService(msrest.serialization.Model):
"""The information of an AutoApprovedPrivateLinkService.
:param private_link_service: The id of the private link service resource.
:type private_link_service: str
"""
_attribute_map = {
'private_link_service': {'key': 'privateLinkService', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AutoApprovedPrivateLinkService, self).__init__(**kwargs)
self.private_link_service = kwargs.get('private_link_service', None)
class AutoApprovedPrivateLinkServicesResult(msrest.serialization.Model):
"""An array of private link service id that can be linked to a private end point with auto approved.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of auto approved private link service.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AutoApprovedPrivateLinkService]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AutoApprovedPrivateLinkService]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AutoApprovedPrivateLinkServicesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class Availability(msrest.serialization.Model):
"""Availability of the metric.
:param time_grain: The time grain of the availability.
:type time_grain: str
:param retention: The retention of the availability.
:type retention: str
:param blob_duration: Duration of the availability blob.
:type blob_duration: str
"""
_attribute_map = {
'time_grain': {'key': 'timeGrain', 'type': 'str'},
'retention': {'key': 'retention', 'type': 'str'},
'blob_duration': {'key': 'blobDuration', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Availability, self).__init__(**kwargs)
self.time_grain = kwargs.get('time_grain', None)
self.retention = kwargs.get('retention', None)
self.blob_duration = kwargs.get('blob_duration', None)
class AvailableDelegation(msrest.serialization.Model):
"""The serviceName of an AvailableDelegation indicates a possible delegation for a subnet.
:param name: The name of the AvailableDelegation resource.
:type name: str
:param id: A unique identifier of the AvailableDelegation resource.
:type id: str
:param type: Resource type.
:type type: str
:param service_name: The name of the service and resource.
:type service_name: str
:param actions: The actions permitted to the service upon delegation.
:type actions: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'service_name': {'key': 'serviceName', 'type': 'str'},
'actions': {'key': 'actions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AvailableDelegation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.service_name = kwargs.get('service_name', None)
self.actions = kwargs.get('actions', None)
class AvailableDelegationsResult(msrest.serialization.Model):
"""An array of available delegations.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of available delegations.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AvailableDelegation]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AvailableDelegation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableDelegationsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AvailablePrivateEndpointType(msrest.serialization.Model):
"""The information of an AvailablePrivateEndpointType.
:param name: The name of the service and resource.
:type name: str
:param id: A unique identifier of the AvailablePrivateEndpoint Type resource.
:type id: str
:param type: Resource type.
:type type: str
:param resource_name: The name of the service and resource.
:type resource_name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'resource_name': {'key': 'resourceName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailablePrivateEndpointType, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.resource_name = kwargs.get('resource_name', None)
class AvailablePrivateEndpointTypesResult(msrest.serialization.Model):
"""An array of available PrivateEndpoint types.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of available privateEndpoint type.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AvailablePrivateEndpointType]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AvailablePrivateEndpointType]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailablePrivateEndpointTypesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AvailableProvidersList(msrest.serialization.Model):
"""List of available countries with details.
All required parameters must be populated in order to send to Azure.
:param countries: Required. List of available countries.
:type countries: list[~azure.mgmt.network.v2020_04_01.models.AvailableProvidersListCountry]
"""
_validation = {
'countries': {'required': True},
}
_attribute_map = {
'countries': {'key': 'countries', 'type': '[AvailableProvidersListCountry]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersList, self).__init__(**kwargs)
self.countries = kwargs['countries']
class AvailableProvidersListCity(msrest.serialization.Model):
"""City or town details.
:param city_name: The city or town name.
:type city_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
"""
_attribute_map = {
'city_name': {'key': 'cityName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListCity, self).__init__(**kwargs)
self.city_name = kwargs.get('city_name', None)
self.providers = kwargs.get('providers', None)
class AvailableProvidersListCountry(msrest.serialization.Model):
"""Country details.
:param country_name: The country name.
:type country_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
:param states: List of available states in the country.
:type states: list[~azure.mgmt.network.v2020_04_01.models.AvailableProvidersListState]
"""
_attribute_map = {
'country_name': {'key': 'countryName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
'states': {'key': 'states', 'type': '[AvailableProvidersListState]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListCountry, self).__init__(**kwargs)
self.country_name = kwargs.get('country_name', None)
self.providers = kwargs.get('providers', None)
self.states = kwargs.get('states', None)
class AvailableProvidersListParameters(msrest.serialization.Model):
"""Constraints that determine the list of available Internet service providers.
:param azure_locations: A list of Azure regions.
:type azure_locations: list[str]
:param country: The country for available providers list.
:type country: str
:param state: The state for available providers list.
:type state: str
:param city: The city or town for available providers list.
:type city: str
"""
_attribute_map = {
'azure_locations': {'key': 'azureLocations', 'type': '[str]'},
'country': {'key': 'country', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'city': {'key': 'city', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListParameters, self).__init__(**kwargs)
self.azure_locations = kwargs.get('azure_locations', None)
self.country = kwargs.get('country', None)
self.state = kwargs.get('state', None)
self.city = kwargs.get('city', None)
class AvailableProvidersListState(msrest.serialization.Model):
"""State details.
:param state_name: The state name.
:type state_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
:param cities: List of available cities or towns in the state.
:type cities: list[~azure.mgmt.network.v2020_04_01.models.AvailableProvidersListCity]
"""
_attribute_map = {
'state_name': {'key': 'stateName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
'cities': {'key': 'cities', 'type': '[AvailableProvidersListCity]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListState, self).__init__(**kwargs)
self.state_name = kwargs.get('state_name', None)
self.providers = kwargs.get('providers', None)
self.cities = kwargs.get('cities', None)
class AvailableServiceAlias(msrest.serialization.Model):
"""The available service alias.
:param name: The name of the service alias.
:type name: str
:param id: The ID of the service alias.
:type id: str
:param type: The type of the resource.
:type type: str
:param resource_name: The resource name of the service alias.
:type resource_name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'resource_name': {'key': 'resourceName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableServiceAlias, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.resource_name = kwargs.get('resource_name', None)
class AvailableServiceAliasesResult(msrest.serialization.Model):
"""An array of available service aliases.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of available service aliases.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AvailableServiceAlias]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AvailableServiceAlias]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableServiceAliasesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AzureAsyncOperationResult(msrest.serialization.Model):
"""The response body contains the status of the specified asynchronous operation, indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous operation succeeded, the response body includes the HTTP status code for the successful request. If the asynchronous operation failed, the response body includes the HTTP status code for the failed request and error information regarding the failure.
:param status: Status of the Azure async operation. Possible values include: "InProgress",
"Succeeded", "Failed".
:type status: str or ~azure.mgmt.network.v2020_04_01.models.NetworkOperationStatus
:param error: Details of the error occurred during specified asynchronous operation.
:type error: ~azure.mgmt.network.v2020_04_01.models.Error
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'error': {'key': 'error', 'type': 'Error'},
}
def __init__(
self,
**kwargs
):
super(AzureAsyncOperationResult, self).__init__(**kwargs)
self.status = kwargs.get('status', None)
self.error = kwargs.get('error', None)
class AzureFirewall(Resource):
"""Azure Firewall resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param zones: A list of availability zones denoting where the resource needs to come from.
:type zones: list[str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param application_rule_collections: Collection of application rule collections used by Azure
Firewall.
:type application_rule_collections:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallApplicationRuleCollection]
:param nat_rule_collections: Collection of NAT rule collections used by Azure Firewall.
:type nat_rule_collections:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallNatRuleCollection]
:param network_rule_collections: Collection of network rule collections used by Azure Firewall.
:type network_rule_collections:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallNetworkRuleCollection]
:param ip_configurations: IP configuration of the Azure Firewall resource.
:type ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallIPConfiguration]
:param management_ip_configuration: IP configuration of the Azure Firewall used for management
traffic.
:type management_ip_configuration:
~azure.mgmt.network.v2020_04_01.models.AzureFirewallIPConfiguration
:ivar provisioning_state: The provisioning state of the Azure firewall resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param threat_intel_mode: The operation mode for Threat Intelligence. Possible values include:
"Alert", "Deny", "Off".
:type threat_intel_mode: str or
~azure.mgmt.network.v2020_04_01.models.AzureFirewallThreatIntelMode
:param virtual_hub: The virtualHub to which the firewall belongs.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param firewall_policy: The firewallPolicy associated with this azure firewall.
:type firewall_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar hub_ip_addresses: IP addresses associated with AzureFirewall.
:vartype hub_ip_addresses: ~azure.mgmt.network.v2020_04_01.models.HubIPAddresses
:ivar ip_groups: IpGroups associated with AzureFirewall.
:vartype ip_groups: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallIpGroups]
:param sku: The Azure Firewall Resource SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.AzureFirewallSku
:param additional_properties: The additional properties used to further config this azure
firewall.
:type additional_properties: dict[str, str]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'hub_ip_addresses': {'readonly': True},
'ip_groups': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'zones': {'key': 'zones', 'type': '[str]'},
'etag': {'key': 'etag', 'type': 'str'},
'application_rule_collections': {'key': 'properties.applicationRuleCollections', 'type': '[AzureFirewallApplicationRuleCollection]'},
'nat_rule_collections': {'key': 'properties.natRuleCollections', 'type': '[AzureFirewallNatRuleCollection]'},
'network_rule_collections': {'key': 'properties.networkRuleCollections', 'type': '[AzureFirewallNetworkRuleCollection]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[AzureFirewallIPConfiguration]'},
'management_ip_configuration': {'key': 'properties.managementIpConfiguration', 'type': 'AzureFirewallIPConfiguration'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'threat_intel_mode': {'key': 'properties.threatIntelMode', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'},
'hub_ip_addresses': {'key': 'properties.hubIpAddresses', 'type': 'HubIPAddresses'},
'ip_groups': {'key': 'properties.ipGroups', 'type': '[AzureFirewallIpGroups]'},
'sku': {'key': 'properties.sku', 'type': 'AzureFirewallSku'},
'additional_properties': {'key': 'properties.additionalProperties', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewall, self).__init__(**kwargs)
self.zones = kwargs.get('zones', None)
self.etag = None
self.application_rule_collections = kwargs.get('application_rule_collections', None)
self.nat_rule_collections = kwargs.get('nat_rule_collections', None)
self.network_rule_collections = kwargs.get('network_rule_collections', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.management_ip_configuration = kwargs.get('management_ip_configuration', None)
self.provisioning_state = None
self.threat_intel_mode = kwargs.get('threat_intel_mode', None)
self.virtual_hub = kwargs.get('virtual_hub', None)
self.firewall_policy = kwargs.get('firewall_policy', None)
self.hub_ip_addresses = None
self.ip_groups = None
self.sku = kwargs.get('sku', None)
self.additional_properties = kwargs.get('additional_properties', None)
class AzureFirewallApplicationRule(msrest.serialization.Model):
"""Properties of an application rule.
:param name: Name of the application rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param protocols: Array of ApplicationRuleProtocols.
:type protocols:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallApplicationRuleProtocol]
:param target_fqdns: List of FQDNs for this rule.
:type target_fqdns: list[str]
:param fqdn_tags: List of FQDN Tags for this rule.
:type fqdn_tags: list[str]
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'protocols': {'key': 'protocols', 'type': '[AzureFirewallApplicationRuleProtocol]'},
'target_fqdns': {'key': 'targetFqdns', 'type': '[str]'},
'fqdn_tags': {'key': 'fqdnTags', 'type': '[str]'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.protocols = kwargs.get('protocols', None)
self.target_fqdns = kwargs.get('target_fqdns', None)
self.fqdn_tags = kwargs.get('fqdn_tags', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
class AzureFirewallApplicationRuleCollection(SubResource):
"""Application rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the Azure firewall. This name can
be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the application rule collection resource.
:type priority: int
:param action: The action type of a rule collection.
:type action: ~azure.mgmt.network.v2020_04_01.models.AzureFirewallRCAction
:param rules: Collection of rules used by a application rule collection.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallApplicationRule]
:ivar provisioning_state: The provisioning state of the application rule collection resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallApplicationRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallApplicationRuleProtocol(msrest.serialization.Model):
"""Properties of the application rule protocol.
:param protocol_type: Protocol type. Possible values include: "Http", "Https", "Mssql".
:type protocol_type: str or
~azure.mgmt.network.v2020_04_01.models.AzureFirewallApplicationRuleProtocolType
:param port: Port number for the protocol, cannot be greater than 64000. This field is
optional.
:type port: int
"""
_validation = {
'port': {'maximum': 64000, 'minimum': 0},
}
_attribute_map = {
'protocol_type': {'key': 'protocolType', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRuleProtocol, self).__init__(**kwargs)
self.protocol_type = kwargs.get('protocol_type', None)
self.port = kwargs.get('port', None)
class AzureFirewallFqdnTag(Resource):
"""Azure Firewall FQDN Tag Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the Azure firewall FQDN tag resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar fqdn_tag_name: The name of this FQDN Tag.
:vartype fqdn_tag_name: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'fqdn_tag_name': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'fqdn_tag_name': {'key': 'properties.fqdnTagName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallFqdnTag, self).__init__(**kwargs)
self.etag = None
self.provisioning_state = None
self.fqdn_tag_name = None
class AzureFirewallFqdnTagListResult(msrest.serialization.Model):
"""Response for ListAzureFirewallFqdnTags API service call.
:param value: List of Azure Firewall FQDN Tags in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallFqdnTag]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[AzureFirewallFqdnTag]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallFqdnTagListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AzureFirewallIPConfiguration(SubResource):
"""IP configuration of an Azure Firewall.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:ivar private_ip_address: The Firewall Internal Load Balancer IP to be used as the next hop in
User Defined Routes.
:vartype private_ip_address: str
:param subnet: Reference to the subnet resource. This resource must be named
'AzureFirewallSubnet' or 'AzureFirewallManagementSubnet'.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param public_ip_address: Reference to the PublicIP resource. This field is a mandatory input
if subnet is not null.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the Azure firewall IP configuration
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'private_ip_address': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.private_ip_address = None
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
class AzureFirewallIpGroups(msrest.serialization.Model):
"""IpGroups associated with azure firewall.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource ID.
:vartype id: str
:ivar change_number: The iteration number.
:vartype change_number: str
"""
_validation = {
'id': {'readonly': True},
'change_number': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'change_number': {'key': 'changeNumber', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallIpGroups, self).__init__(**kwargs)
self.id = None
self.change_number = None
class AzureFirewallListResult(msrest.serialization.Model):
"""Response for ListAzureFirewalls API service call.
:param value: List of Azure Firewalls in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewall]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[AzureFirewall]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AzureFirewallNatRCAction(msrest.serialization.Model):
"""AzureFirewall NAT Rule Collection Action.
:param type: The type of action. Possible values include: "Snat", "Dnat".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.AzureFirewallNatRCActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRCAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class AzureFirewallNatRule(msrest.serialization.Model):
"""Properties of a NAT rule.
:param name: Name of the NAT rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses for this rule. Supports IP
ranges, prefixes, and service tags.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param protocols: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
:type protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.AzureFirewallNetworkRuleProtocol]
:param translated_address: The translated address for this NAT rule.
:type translated_address: str
:param translated_port: The translated port for this NAT rule.
:type translated_port: str
:param translated_fqdn: The translated FQDN for this NAT rule.
:type translated_fqdn: str
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
'protocols': {'key': 'protocols', 'type': '[str]'},
'translated_address': {'key': 'translatedAddress', 'type': 'str'},
'translated_port': {'key': 'translatedPort', 'type': 'str'},
'translated_fqdn': {'key': 'translatedFqdn', 'type': 'str'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
self.protocols = kwargs.get('protocols', None)
self.translated_address = kwargs.get('translated_address', None)
self.translated_port = kwargs.get('translated_port', None)
self.translated_fqdn = kwargs.get('translated_fqdn', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
class AzureFirewallNatRuleCollection(SubResource):
"""NAT rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the Azure firewall. This name can
be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the NAT rule collection resource.
:type priority: int
:param action: The action type of a NAT rule collection.
:type action: ~azure.mgmt.network.v2020_04_01.models.AzureFirewallNatRCAction
:param rules: Collection of rules used by a NAT rule collection.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallNatRule]
:ivar provisioning_state: The provisioning state of the NAT rule collection resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallNatRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNatRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallNetworkRule(msrest.serialization.Model):
"""Properties of the network rule.
:param name: Name of the network rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param protocols: Array of AzureFirewallNetworkRuleProtocols.
:type protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.AzureFirewallNetworkRuleProtocol]
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param destination_fqdns: List of destination FQDNs.
:type destination_fqdns: list[str]
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
:param destination_ip_groups: List of destination IpGroups for this rule.
:type destination_ip_groups: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'protocols': {'key': 'protocols', 'type': '[str]'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
'destination_fqdns': {'key': 'destinationFqdns', 'type': '[str]'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
'destination_ip_groups': {'key': 'destinationIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNetworkRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.protocols = kwargs.get('protocols', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
self.destination_fqdns = kwargs.get('destination_fqdns', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
self.destination_ip_groups = kwargs.get('destination_ip_groups', None)
class AzureFirewallNetworkRuleCollection(SubResource):
"""Network rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the Azure firewall. This name can
be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the network rule collection resource.
:type priority: int
:param action: The action type of a rule collection.
:type action: ~azure.mgmt.network.v2020_04_01.models.AzureFirewallRCAction
:param rules: Collection of rules used by a network rule collection.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallNetworkRule]
:ivar provisioning_state: The provisioning state of the network rule collection resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNetworkRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNetworkRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallPublicIPAddress(msrest.serialization.Model):
"""Public IP Address associated with azure firewall.
:param address: Public IP Address value.
:type address: str
"""
_attribute_map = {
'address': {'key': 'address', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallPublicIPAddress, self).__init__(**kwargs)
self.address = kwargs.get('address', None)
class AzureFirewallRCAction(msrest.serialization.Model):
"""Properties of the AzureFirewallRCAction.
:param type: The type of action. Possible values include: "Allow", "Deny".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.AzureFirewallRCActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallRCAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class AzureFirewallSku(msrest.serialization.Model):
"""SKU of an Azure Firewall.
:param name: Name of an Azure Firewall SKU. Possible values include: "AZFW_VNet", "AZFW_Hub".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.AzureFirewallSkuName
:param tier: Tier of an Azure Firewall. Possible values include: "Standard", "Premium".
:type tier: str or ~azure.mgmt.network.v2020_04_01.models.AzureFirewallSkuTier
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
class AzureReachabilityReport(msrest.serialization.Model):
"""Azure reachability report details.
All required parameters must be populated in order to send to Azure.
:param aggregation_level: Required. The aggregation level of Azure reachability report. Can be
Country, State or City.
:type aggregation_level: str
:param provider_location: Required. Parameters that define a geographic location.
:type provider_location: ~azure.mgmt.network.v2020_04_01.models.AzureReachabilityReportLocation
:param reachability_report: Required. List of Azure reachability report items.
:type reachability_report:
list[~azure.mgmt.network.v2020_04_01.models.AzureReachabilityReportItem]
"""
_validation = {
'aggregation_level': {'required': True},
'provider_location': {'required': True},
'reachability_report': {'required': True},
}
_attribute_map = {
'aggregation_level': {'key': 'aggregationLevel', 'type': 'str'},
'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'},
'reachability_report': {'key': 'reachabilityReport', 'type': '[AzureReachabilityReportItem]'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReport, self).__init__(**kwargs)
self.aggregation_level = kwargs['aggregation_level']
self.provider_location = kwargs['provider_location']
self.reachability_report = kwargs['reachability_report']
class AzureReachabilityReportItem(msrest.serialization.Model):
"""Azure reachability report details for a given provider location.
:param provider: The Internet service provider.
:type provider: str
:param azure_location: The Azure region.
:type azure_location: str
:param latencies: List of latency details for each of the time series.
:type latencies:
list[~azure.mgmt.network.v2020_04_01.models.AzureReachabilityReportLatencyInfo]
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'azure_location': {'key': 'azureLocation', 'type': 'str'},
'latencies': {'key': 'latencies', 'type': '[AzureReachabilityReportLatencyInfo]'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportItem, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.azure_location = kwargs.get('azure_location', None)
self.latencies = kwargs.get('latencies', None)
class AzureReachabilityReportLatencyInfo(msrest.serialization.Model):
"""Details on latency for a time series.
:param time_stamp: The time stamp.
:type time_stamp: ~datetime.datetime
:param score: The relative latency score between 1 and 100, higher values indicating a faster
connection.
:type score: int
"""
_validation = {
'score': {'maximum': 100, 'minimum': 1},
}
_attribute_map = {
'time_stamp': {'key': 'timeStamp', 'type': 'iso-8601'},
'score': {'key': 'score', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportLatencyInfo, self).__init__(**kwargs)
self.time_stamp = kwargs.get('time_stamp', None)
self.score = kwargs.get('score', None)
class AzureReachabilityReportLocation(msrest.serialization.Model):
"""Parameters that define a geographic location.
All required parameters must be populated in order to send to Azure.
:param country: Required. The name of the country.
:type country: str
:param state: The name of the state.
:type state: str
:param city: The name of the city or town.
:type city: str
"""
_validation = {
'country': {'required': True},
}
_attribute_map = {
'country': {'key': 'country', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'city': {'key': 'city', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportLocation, self).__init__(**kwargs)
self.country = kwargs['country']
self.state = kwargs.get('state', None)
self.city = kwargs.get('city', None)
class AzureReachabilityReportParameters(msrest.serialization.Model):
"""Geographic and time constraints for Azure reachability report.
All required parameters must be populated in order to send to Azure.
:param provider_location: Required. Parameters that define a geographic location.
:type provider_location: ~azure.mgmt.network.v2020_04_01.models.AzureReachabilityReportLocation
:param providers: List of Internet service providers.
:type providers: list[str]
:param azure_locations: Optional Azure regions to scope the query to.
:type azure_locations: list[str]
:param start_time: Required. The start time for the Azure reachability report.
:type start_time: ~datetime.datetime
:param end_time: Required. The end time for the Azure reachability report.
:type end_time: ~datetime.datetime
"""
_validation = {
'provider_location': {'required': True},
'start_time': {'required': True},
'end_time': {'required': True},
}
_attribute_map = {
'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'},
'providers': {'key': 'providers', 'type': '[str]'},
'azure_locations': {'key': 'azureLocations', 'type': '[str]'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportParameters, self).__init__(**kwargs)
self.provider_location = kwargs['provider_location']
self.providers = kwargs.get('providers', None)
self.azure_locations = kwargs.get('azure_locations', None)
self.start_time = kwargs['start_time']
self.end_time = kwargs['end_time']
class BackendAddressPool(SubResource):
"""Pool of backend IP addresses.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of backend address pools
used by the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param load_balancer_backend_addresses: An array of backend addresses.
:type load_balancer_backend_addresses:
list[~azure.mgmt.network.v2020_04_01.models.LoadBalancerBackendAddress]
:ivar backend_ip_configurations: An array of references to IP addresses defined in network
interfaces.
:vartype backend_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration]
:ivar load_balancing_rules: An array of references to load balancing rules that use this
backend address pool.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar outbound_rule: A reference to an outbound rule that uses this backend address pool.
:vartype outbound_rule: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar outbound_rules: An array of references to outbound rules that use this backend address
pool.
:vartype outbound_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the backend address pool resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'backend_ip_configurations': {'readonly': True},
'load_balancing_rules': {'readonly': True},
'outbound_rule': {'readonly': True},
'outbound_rules': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'load_balancer_backend_addresses': {'key': 'properties.loadBalancerBackendAddresses', 'type': '[LoadBalancerBackendAddress]'},
'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'outbound_rule': {'key': 'properties.outboundRule', 'type': 'SubResource'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BackendAddressPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.load_balancer_backend_addresses = kwargs.get('load_balancer_backend_addresses', None)
self.backend_ip_configurations = None
self.load_balancing_rules = None
self.outbound_rule = None
self.outbound_rules = None
self.provisioning_state = None
class BastionActiveSession(msrest.serialization.Model):
"""The session detail for a target.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar session_id: A unique id for the session.
:vartype session_id: str
:ivar start_time: The time when the session started.
:vartype start_time: any
:ivar target_subscription_id: The subscription id for the target virtual machine.
:vartype target_subscription_id: str
:ivar resource_type: The type of the resource.
:vartype resource_type: str
:ivar target_host_name: The host name of the target.
:vartype target_host_name: str
:ivar target_resource_group: The resource group of the target.
:vartype target_resource_group: str
:ivar user_name: The user name who is active on this session.
:vartype user_name: str
:ivar target_ip_address: The IP Address of the target.
:vartype target_ip_address: str
:ivar protocol: The protocol used to connect to the target. Possible values include: "SSH",
"RDP".
:vartype protocol: str or ~azure.mgmt.network.v2020_04_01.models.BastionConnectProtocol
:ivar target_resource_id: The resource id of the target.
:vartype target_resource_id: str
:ivar session_duration_in_mins: Duration in mins the session has been active.
:vartype session_duration_in_mins: float
"""
_validation = {
'session_id': {'readonly': True},
'start_time': {'readonly': True},
'target_subscription_id': {'readonly': True},
'resource_type': {'readonly': True},
'target_host_name': {'readonly': True},
'target_resource_group': {'readonly': True},
'user_name': {'readonly': True},
'target_ip_address': {'readonly': True},
'protocol': {'readonly': True},
'target_resource_id': {'readonly': True},
'session_duration_in_mins': {'readonly': True},
}
_attribute_map = {
'session_id': {'key': 'sessionId', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'object'},
'target_subscription_id': {'key': 'targetSubscriptionId', 'type': 'str'},
'resource_type': {'key': 'resourceType', 'type': 'str'},
'target_host_name': {'key': 'targetHostName', 'type': 'str'},
'target_resource_group': {'key': 'targetResourceGroup', 'type': 'str'},
'user_name': {'key': 'userName', 'type': 'str'},
'target_ip_address': {'key': 'targetIpAddress', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'session_duration_in_mins': {'key': 'sessionDurationInMins', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(BastionActiveSession, self).__init__(**kwargs)
self.session_id = None
self.start_time = None
self.target_subscription_id = None
self.resource_type = None
self.target_host_name = None
self.target_resource_group = None
self.user_name = None
self.target_ip_address = None
self.protocol = None
self.target_resource_id = None
self.session_duration_in_mins = None
class BastionActiveSessionListResult(msrest.serialization.Model):
"""Response for GetActiveSessions.
:param value: List of active sessions on the bastion.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BastionActiveSession]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BastionActiveSession]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionActiveSessionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BastionHost(Resource):
"""Bastion Host resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param ip_configurations: IP configuration of the Bastion Host resource.
:type ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.BastionHostIPConfiguration]
:param dns_name: FQDN for the endpoint on which bastion host is accessible.
:type dns_name: str
:ivar provisioning_state: The provisioning state of the bastion host resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[BastionHostIPConfiguration]'},
'dns_name': {'key': 'properties.dnsName', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHost, self).__init__(**kwargs)
self.etag = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.dns_name = kwargs.get('dns_name', None)
self.provisioning_state = None
class BastionHostIPConfiguration(SubResource):
"""IP configuration of an Bastion Host.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Ip configuration type.
:vartype type: str
:param subnet: Reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param public_ip_address: Reference of the PublicIP resource.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the bastion host IP configuration resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_ip_allocation_method: Private IP allocation method. Possible values include:
"Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHostIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
class BastionHostListResult(msrest.serialization.Model):
"""Response for ListBastionHosts API service call.
:param value: List of Bastion Hosts in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BastionHost]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BastionHost]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHostListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BastionSessionDeleteResult(msrest.serialization.Model):
"""Response for DisconnectActiveSessions.
:param value: List of sessions with their corresponding state.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BastionSessionState]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BastionSessionState]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionSessionDeleteResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BastionSessionState(msrest.serialization.Model):
"""The session state detail for a target.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar session_id: A unique id for the session.
:vartype session_id: str
:ivar message: Used for extra information.
:vartype message: str
:ivar state: The state of the session. Disconnected/Failed/NotFound.
:vartype state: str
"""
_validation = {
'session_id': {'readonly': True},
'message': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'session_id': {'key': 'sessionId', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionSessionState, self).__init__(**kwargs)
self.session_id = None
self.message = None
self.state = None
class BastionShareableLink(msrest.serialization.Model):
"""Bastion Shareable Link.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param vm: Required. Reference of the virtual machine resource.
:type vm: ~azure.mgmt.network.v2020_04_01.models.VM
:ivar bsl: The unique Bastion Shareable Link to the virtual machine.
:vartype bsl: str
:ivar created_at: The time when the link was created.
:vartype created_at: str
:ivar message: Optional field indicating the warning or error message related to the vm in case
of partial failure.
:vartype message: str
"""
_validation = {
'vm': {'required': True},
'bsl': {'readonly': True},
'created_at': {'readonly': True},
'message': {'readonly': True},
}
_attribute_map = {
'vm': {'key': 'vm', 'type': 'VM'},
'bsl': {'key': 'bsl', 'type': 'str'},
'created_at': {'key': 'createdAt', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionShareableLink, self).__init__(**kwargs)
self.vm = kwargs['vm']
self.bsl = None
self.created_at = None
self.message = None
class BastionShareableLinkListRequest(msrest.serialization.Model):
"""Post request for all the Bastion Shareable Link endpoints.
:param vms: List of VM references.
:type vms: list[~azure.mgmt.network.v2020_04_01.models.BastionShareableLink]
"""
_attribute_map = {
'vms': {'key': 'vms', 'type': '[BastionShareableLink]'},
}
def __init__(
self,
**kwargs
):
super(BastionShareableLinkListRequest, self).__init__(**kwargs)
self.vms = kwargs.get('vms', None)
class BastionShareableLinkListResult(msrest.serialization.Model):
"""Response for all the Bastion Shareable Link endpoints.
:param value: List of Bastion Shareable Links for the request.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BastionShareableLink]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BastionShareableLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionShareableLinkListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BGPCommunity(msrest.serialization.Model):
"""Contains bgp community information offered in Service Community resources.
:param service_supported_region: The region which the service support. e.g. For O365, region is
Global.
:type service_supported_region: str
:param community_name: The name of the bgp community. e.g. Skype.
:type community_name: str
:param community_value: The value of the bgp community. For more information:
https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing.
:type community_value: str
:param community_prefixes: The prefixes that the bgp community contains.
:type community_prefixes: list[str]
:param is_authorized_to_use: Customer is authorized to use bgp community or not.
:type is_authorized_to_use: bool
:param service_group: The service group of the bgp community contains.
:type service_group: str
"""
_attribute_map = {
'service_supported_region': {'key': 'serviceSupportedRegion', 'type': 'str'},
'community_name': {'key': 'communityName', 'type': 'str'},
'community_value': {'key': 'communityValue', 'type': 'str'},
'community_prefixes': {'key': 'communityPrefixes', 'type': '[str]'},
'is_authorized_to_use': {'key': 'isAuthorizedToUse', 'type': 'bool'},
'service_group': {'key': 'serviceGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BGPCommunity, self).__init__(**kwargs)
self.service_supported_region = kwargs.get('service_supported_region', None)
self.community_name = kwargs.get('community_name', None)
self.community_value = kwargs.get('community_value', None)
self.community_prefixes = kwargs.get('community_prefixes', None)
self.is_authorized_to_use = kwargs.get('is_authorized_to_use', None)
self.service_group = kwargs.get('service_group', None)
class BgpPeerStatus(msrest.serialization.Model):
"""BGP peer status details.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar local_address: The virtual network gateway's local address.
:vartype local_address: str
:ivar neighbor: The remote BGP peer.
:vartype neighbor: str
:ivar asn: The autonomous system number of the remote BGP peer.
:vartype asn: long
:ivar state: The BGP peer state. Possible values include: "Unknown", "Stopped", "Idle",
"Connecting", "Connected".
:vartype state: str or ~azure.mgmt.network.v2020_04_01.models.BgpPeerState
:ivar connected_duration: For how long the peering has been up.
:vartype connected_duration: str
:ivar routes_received: The number of routes learned from this peer.
:vartype routes_received: long
:ivar messages_sent: The number of BGP messages sent.
:vartype messages_sent: long
:ivar messages_received: The number of BGP messages received.
:vartype messages_received: long
"""
_validation = {
'local_address': {'readonly': True},
'neighbor': {'readonly': True},
'asn': {'readonly': True, 'maximum': 4294967295, 'minimum': 0},
'state': {'readonly': True},
'connected_duration': {'readonly': True},
'routes_received': {'readonly': True},
'messages_sent': {'readonly': True},
'messages_received': {'readonly': True},
}
_attribute_map = {
'local_address': {'key': 'localAddress', 'type': 'str'},
'neighbor': {'key': 'neighbor', 'type': 'str'},
'asn': {'key': 'asn', 'type': 'long'},
'state': {'key': 'state', 'type': 'str'},
'connected_duration': {'key': 'connectedDuration', 'type': 'str'},
'routes_received': {'key': 'routesReceived', 'type': 'long'},
'messages_sent': {'key': 'messagesSent', 'type': 'long'},
'messages_received': {'key': 'messagesReceived', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(BgpPeerStatus, self).__init__(**kwargs)
self.local_address = None
self.neighbor = None
self.asn = None
self.state = None
self.connected_duration = None
self.routes_received = None
self.messages_sent = None
self.messages_received = None
class BgpPeerStatusListResult(msrest.serialization.Model):
"""Response for list BGP peer status API service call.
:param value: List of BGP peers.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BgpPeerStatus]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BgpPeerStatus]'},
}
def __init__(
self,
**kwargs
):
super(BgpPeerStatusListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class BgpServiceCommunity(Resource):
"""Service Community Properties.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param service_name: The name of the bgp community. e.g. Skype.
:type service_name: str
:param bgp_communities: A list of bgp communities.
:type bgp_communities: list[~azure.mgmt.network.v2020_04_01.models.BGPCommunity]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'service_name': {'key': 'properties.serviceName', 'type': 'str'},
'bgp_communities': {'key': 'properties.bgpCommunities', 'type': '[BGPCommunity]'},
}
def __init__(
self,
**kwargs
):
super(BgpServiceCommunity, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.bgp_communities = kwargs.get('bgp_communities', None)
class BgpServiceCommunityListResult(msrest.serialization.Model):
"""Response for the ListServiceCommunity API service call.
:param value: A list of service community resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BgpServiceCommunity]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BgpServiceCommunity]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BgpServiceCommunityListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BgpSettings(msrest.serialization.Model):
"""BGP settings details.
:param asn: The BGP speaker's ASN.
:type asn: long
:param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker.
:type bgp_peering_address: str
:param peer_weight: The weight added to routes learned from this BGP speaker.
:type peer_weight: int
:param bgp_peering_addresses: BGP peering address with IP configuration ID for virtual network
gateway.
:type bgp_peering_addresses:
list[~azure.mgmt.network.v2020_04_01.models.IPConfigurationBgpPeeringAddress]
"""
_validation = {
'asn': {'maximum': 4294967295, 'minimum': 0},
}
_attribute_map = {
'asn': {'key': 'asn', 'type': 'long'},
'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
'peer_weight': {'key': 'peerWeight', 'type': 'int'},
'bgp_peering_addresses': {'key': 'bgpPeeringAddresses', 'type': '[IPConfigurationBgpPeeringAddress]'},
}
def __init__(
self,
**kwargs
):
super(BgpSettings, self).__init__(**kwargs)
self.asn = kwargs.get('asn', None)
self.bgp_peering_address = kwargs.get('bgp_peering_address', None)
self.peer_weight = kwargs.get('peer_weight', None)
self.bgp_peering_addresses = kwargs.get('bgp_peering_addresses', None)
class CheckPrivateLinkServiceVisibilityRequest(msrest.serialization.Model):
"""Request body of the CheckPrivateLinkServiceVisibility API service call.
:param private_link_service_alias: The alias of the private link service.
:type private_link_service_alias: str
"""
_attribute_map = {
'private_link_service_alias': {'key': 'privateLinkServiceAlias', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CheckPrivateLinkServiceVisibilityRequest, self).__init__(**kwargs)
self.private_link_service_alias = kwargs.get('private_link_service_alias', None)
class CloudErrorBody(msrest.serialization.Model):
"""An error response from the service.
:param code: An identifier for the error. Codes are invariant and are intended to be consumed
programmatically.
:type code: str
:param message: A message describing the error, intended to be suitable for display in a user
interface.
:type message: str
:param target: The target of the particular error. For example, the name of the property in
error.
:type target: str
:param details: A list of additional details about the error.
:type details: list[~azure.mgmt.network.v2020_04_01.models.CloudErrorBody]
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[CloudErrorBody]'},
}
def __init__(
self,
**kwargs
):
super(CloudErrorBody, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.message = kwargs.get('message', None)
self.target = kwargs.get('target', None)
self.details = kwargs.get('details', None)
class Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties(msrest.serialization.Model):
"""Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of user assigned identity.
:vartype principal_id: str
:ivar client_id: The client id of user assigned identity.
:vartype client_id: str
"""
_validation = {
'principal_id': {'readonly': True},
'client_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'client_id': {'key': 'clientId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties, self).__init__(**kwargs)
self.principal_id = None
self.client_id = None
class ConnectionMonitor(msrest.serialization.Model):
"""Parameters that define the operation to create a connection monitor.
:param location: Connection monitor location.
:type location: str
:param tags: A set of tags. Connection monitor tags.
:type tags: dict[str, str]
:param source: Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSource
:param destination: Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:param endpoints: List of connection monitor endpoints.
:type endpoints: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpoint]
:param test_configurations: List of connection monitor test configurations.
:type test_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestConfiguration]
:param test_groups: List of connection monitor test groups.
:type test_groups: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestGroup]
:param outputs: List of connection monitor outputs.
:type outputs: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorOutput]
:param notes: Optional notes to be associated with the connection monitor.
:type notes: str
"""
_attribute_map = {
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'properties.autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'},
'endpoints': {'key': 'properties.endpoints', 'type': '[ConnectionMonitorEndpoint]'},
'test_configurations': {'key': 'properties.testConfigurations', 'type': '[ConnectionMonitorTestConfiguration]'},
'test_groups': {'key': 'properties.testGroups', 'type': '[ConnectionMonitorTestGroup]'},
'outputs': {'key': 'properties.outputs', 'type': '[ConnectionMonitorOutput]'},
'notes': {'key': 'properties.notes', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitor, self).__init__(**kwargs)
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.source = kwargs.get('source', None)
self.destination = kwargs.get('destination', None)
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
self.endpoints = kwargs.get('endpoints', None)
self.test_configurations = kwargs.get('test_configurations', None)
self.test_groups = kwargs.get('test_groups', None)
self.outputs = kwargs.get('outputs', None)
self.notes = kwargs.get('notes', None)
class ConnectionMonitorDestination(msrest.serialization.Model):
"""Describes the destination of connection monitor.
:param resource_id: The ID of the resource used as the destination by connection monitor.
:type resource_id: str
:param address: Address of the connection monitor destination (IP or domain name).
:type address: str
:param port: The destination port used by connection monitor.
:type port: int
"""
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorDestination, self).__init__(**kwargs)
self.resource_id = kwargs.get('resource_id', None)
self.address = kwargs.get('address', None)
self.port = kwargs.get('port', None)
class ConnectionMonitorEndpoint(msrest.serialization.Model):
"""Describes the connection monitor endpoint.
All required parameters must be populated in order to send to Azure.
:param name: Required. The name of the connection monitor endpoint.
:type name: str
:param resource_id: Resource ID of the connection monitor endpoint.
:type resource_id: str
:param address: Address of the connection monitor endpoint (IP or domain name).
:type address: str
:param filter: Filter for sub-items within the endpoint.
:type filter: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpointFilter
"""
_validation = {
'name': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'filter': {'key': 'filter', 'type': 'ConnectionMonitorEndpointFilter'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorEndpoint, self).__init__(**kwargs)
self.name = kwargs['name']
self.resource_id = kwargs.get('resource_id', None)
self.address = kwargs.get('address', None)
self.filter = kwargs.get('filter', None)
class ConnectionMonitorEndpointFilter(msrest.serialization.Model):
"""Describes the connection monitor endpoint filter.
:param type: The behavior of the endpoint filter. Currently only 'Include' is supported.
Possible values include: "Include".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpointFilterType
:param items: List of items in the filter.
:type items: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpointFilterItem]
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'items': {'key': 'items', 'type': '[ConnectionMonitorEndpointFilterItem]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorEndpointFilter, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
self.items = kwargs.get('items', None)
class ConnectionMonitorEndpointFilterItem(msrest.serialization.Model):
"""Describes the connection monitor endpoint filter item.
:param type: The type of item included in the filter. Currently only 'AgentAddress' is
supported. Possible values include: "AgentAddress".
:type type: str or
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpointFilterItemType
:param address: The address of the filter item.
:type address: str
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorEndpointFilterItem, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
self.address = kwargs.get('address', None)
class ConnectionMonitorHttpConfiguration(msrest.serialization.Model):
"""Describes the HTTP configuration.
:param port: The port to connect to.
:type port: int
:param method: The HTTP method to use. Possible values include: "Get", "Post".
:type method: str or ~azure.mgmt.network.v2020_04_01.models.HTTPConfigurationMethod
:param path: The path component of the URI. For instance, "/dir1/dir2".
:type path: str
:param request_headers: The HTTP headers to transmit with the request.
:type request_headers: list[~azure.mgmt.network.v2020_04_01.models.HTTPHeader]
:param valid_status_code_ranges: HTTP status codes to consider successful. For instance,
"2xx,301-304,418".
:type valid_status_code_ranges: list[str]
:param prefer_https: Value indicating whether HTTPS is preferred over HTTP in cases where the
choice is not explicit.
:type prefer_https: bool
"""
_attribute_map = {
'port': {'key': 'port', 'type': 'int'},
'method': {'key': 'method', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'},
'request_headers': {'key': 'requestHeaders', 'type': '[HTTPHeader]'},
'valid_status_code_ranges': {'key': 'validStatusCodeRanges', 'type': '[str]'},
'prefer_https': {'key': 'preferHTTPS', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorHttpConfiguration, self).__init__(**kwargs)
self.port = kwargs.get('port', None)
self.method = kwargs.get('method', None)
self.path = kwargs.get('path', None)
self.request_headers = kwargs.get('request_headers', None)
self.valid_status_code_ranges = kwargs.get('valid_status_code_ranges', None)
self.prefer_https = kwargs.get('prefer_https', None)
class ConnectionMonitorIcmpConfiguration(msrest.serialization.Model):
"""Describes the ICMP configuration.
:param disable_trace_route: Value indicating whether path evaluation with trace route should be
disabled.
:type disable_trace_route: bool
"""
_attribute_map = {
'disable_trace_route': {'key': 'disableTraceRoute', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorIcmpConfiguration, self).__init__(**kwargs)
self.disable_trace_route = kwargs.get('disable_trace_route', None)
class ConnectionMonitorListResult(msrest.serialization.Model):
"""List of connection monitors.
:param value: Information about connection monitors.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorResult]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConnectionMonitorResult]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConnectionMonitorOutput(msrest.serialization.Model):
"""Describes a connection monitor output destination.
:param type: Connection monitor output destination type. Currently, only "Workspace" is
supported. Possible values include: "Workspace".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.OutputType
:param workspace_settings: Describes the settings for producing output into a log analytics
workspace.
:type workspace_settings:
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorWorkspaceSettings
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'workspace_settings': {'key': 'workspaceSettings', 'type': 'ConnectionMonitorWorkspaceSettings'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorOutput, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
self.workspace_settings = kwargs.get('workspace_settings', None)
class ConnectionMonitorParameters(msrest.serialization.Model):
"""Parameters that define the operation to create a connection monitor.
:param source: Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSource
:param destination: Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:param endpoints: List of connection monitor endpoints.
:type endpoints: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpoint]
:param test_configurations: List of connection monitor test configurations.
:type test_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestConfiguration]
:param test_groups: List of connection monitor test groups.
:type test_groups: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestGroup]
:param outputs: List of connection monitor outputs.
:type outputs: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorOutput]
:param notes: Optional notes to be associated with the connection monitor.
:type notes: str
"""
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'},
'endpoints': {'key': 'endpoints', 'type': '[ConnectionMonitorEndpoint]'},
'test_configurations': {'key': 'testConfigurations', 'type': '[ConnectionMonitorTestConfiguration]'},
'test_groups': {'key': 'testGroups', 'type': '[ConnectionMonitorTestGroup]'},
'outputs': {'key': 'outputs', 'type': '[ConnectionMonitorOutput]'},
'notes': {'key': 'notes', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorParameters, self).__init__(**kwargs)
self.source = kwargs.get('source', None)
self.destination = kwargs.get('destination', None)
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
self.endpoints = kwargs.get('endpoints', None)
self.test_configurations = kwargs.get('test_configurations', None)
self.test_groups = kwargs.get('test_groups', None)
self.outputs = kwargs.get('outputs', None)
self.notes = kwargs.get('notes', None)
class ConnectionMonitorQueryResult(msrest.serialization.Model):
"""List of connection states snapshots.
:param source_status: Status of connection monitor source. Possible values include: "Unknown",
"Active", "Inactive".
:type source_status: str or
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSourceStatus
:param states: Information about connection states.
:type states: list[~azure.mgmt.network.v2020_04_01.models.ConnectionStateSnapshot]
"""
_attribute_map = {
'source_status': {'key': 'sourceStatus', 'type': 'str'},
'states': {'key': 'states', 'type': '[ConnectionStateSnapshot]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorQueryResult, self).__init__(**kwargs)
self.source_status = kwargs.get('source_status', None)
self.states = kwargs.get('states', None)
class ConnectionMonitorResult(msrest.serialization.Model):
"""Information about the connection monitor.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the connection monitor.
:vartype name: str
:ivar id: ID of the connection monitor.
:vartype id: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Connection monitor type.
:vartype type: str
:param location: Connection monitor location.
:type location: str
:param tags: A set of tags. Connection monitor tags.
:type tags: dict[str, str]
:param source: Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSource
:param destination: Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:param endpoints: List of connection monitor endpoints.
:type endpoints: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpoint]
:param test_configurations: List of connection monitor test configurations.
:type test_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestConfiguration]
:param test_groups: List of connection monitor test groups.
:type test_groups: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestGroup]
:param outputs: List of connection monitor outputs.
:type outputs: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorOutput]
:param notes: Optional notes to be associated with the connection monitor.
:type notes: str
:ivar provisioning_state: The provisioning state of the connection monitor. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar start_time: The date and time when the connection monitor was started.
:vartype start_time: ~datetime.datetime
:ivar monitoring_status: The monitoring status of the connection monitor.
:vartype monitoring_status: str
:ivar connection_monitor_type: Type of connection monitor. Possible values include:
"MultiEndpoint", "SingleSourceDestination".
:vartype connection_monitor_type: str or
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorType
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
'start_time': {'readonly': True},
'monitoring_status': {'readonly': True},
'connection_monitor_type': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'properties.autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'},
'endpoints': {'key': 'properties.endpoints', 'type': '[ConnectionMonitorEndpoint]'},
'test_configurations': {'key': 'properties.testConfigurations', 'type': '[ConnectionMonitorTestConfiguration]'},
'test_groups': {'key': 'properties.testGroups', 'type': '[ConnectionMonitorTestGroup]'},
'outputs': {'key': 'properties.outputs', 'type': '[ConnectionMonitorOutput]'},
'notes': {'key': 'properties.notes', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},
'monitoring_status': {'key': 'properties.monitoringStatus', 'type': 'str'},
'connection_monitor_type': {'key': 'properties.connectionMonitorType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.etag = None
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.source = kwargs.get('source', None)
self.destination = kwargs.get('destination', None)
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
self.endpoints = kwargs.get('endpoints', None)
self.test_configurations = kwargs.get('test_configurations', None)
self.test_groups = kwargs.get('test_groups', None)
self.outputs = kwargs.get('outputs', None)
self.notes = kwargs.get('notes', None)
self.provisioning_state = None
self.start_time = None
self.monitoring_status = None
self.connection_monitor_type = None
class ConnectionMonitorResultProperties(ConnectionMonitorParameters):
"""Describes the properties of a connection monitor.
Variables are only populated by the server, and will be ignored when sending a request.
:param source: Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSource
:param destination: Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:param endpoints: List of connection monitor endpoints.
:type endpoints: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorEndpoint]
:param test_configurations: List of connection monitor test configurations.
:type test_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestConfiguration]
:param test_groups: List of connection monitor test groups.
:type test_groups: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestGroup]
:param outputs: List of connection monitor outputs.
:type outputs: list[~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorOutput]
:param notes: Optional notes to be associated with the connection monitor.
:type notes: str
:ivar provisioning_state: The provisioning state of the connection monitor. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar start_time: The date and time when the connection monitor was started.
:vartype start_time: ~datetime.datetime
:ivar monitoring_status: The monitoring status of the connection monitor.
:vartype monitoring_status: str
:ivar connection_monitor_type: Type of connection monitor. Possible values include:
"MultiEndpoint", "SingleSourceDestination".
:vartype connection_monitor_type: str or
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorType
"""
_validation = {
'provisioning_state': {'readonly': True},
'start_time': {'readonly': True},
'monitoring_status': {'readonly': True},
'connection_monitor_type': {'readonly': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'},
'endpoints': {'key': 'endpoints', 'type': '[ConnectionMonitorEndpoint]'},
'test_configurations': {'key': 'testConfigurations', 'type': '[ConnectionMonitorTestConfiguration]'},
'test_groups': {'key': 'testGroups', 'type': '[ConnectionMonitorTestGroup]'},
'outputs': {'key': 'outputs', 'type': '[ConnectionMonitorOutput]'},
'notes': {'key': 'notes', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'monitoring_status': {'key': 'monitoringStatus', 'type': 'str'},
'connection_monitor_type': {'key': 'connectionMonitorType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorResultProperties, self).__init__(**kwargs)
self.provisioning_state = None
self.start_time = None
self.monitoring_status = None
self.connection_monitor_type = None
class ConnectionMonitorSource(msrest.serialization.Model):
"""Describes the source of connection monitor.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource used as the source by connection monitor.
:type resource_id: str
:param port: The source port used by connection monitor.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorSource, self).__init__(**kwargs)
self.resource_id = kwargs['resource_id']
self.port = kwargs.get('port', None)
class ConnectionMonitorSuccessThreshold(msrest.serialization.Model):
"""Describes the threshold for declaring a test successful.
:param checks_failed_percent: The maximum percentage of failed checks permitted for a test to
evaluate as successful.
:type checks_failed_percent: int
:param round_trip_time_ms: The maximum round-trip time in milliseconds permitted for a test to
evaluate as successful.
:type round_trip_time_ms: float
"""
_attribute_map = {
'checks_failed_percent': {'key': 'checksFailedPercent', 'type': 'int'},
'round_trip_time_ms': {'key': 'roundTripTimeMs', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorSuccessThreshold, self).__init__(**kwargs)
self.checks_failed_percent = kwargs.get('checks_failed_percent', None)
self.round_trip_time_ms = kwargs.get('round_trip_time_ms', None)
class ConnectionMonitorTcpConfiguration(msrest.serialization.Model):
"""Describes the TCP configuration.
:param port: The port to connect to.
:type port: int
:param disable_trace_route: Value indicating whether path evaluation with trace route should be
disabled.
:type disable_trace_route: bool
"""
_attribute_map = {
'port': {'key': 'port', 'type': 'int'},
'disable_trace_route': {'key': 'disableTraceRoute', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorTcpConfiguration, self).__init__(**kwargs)
self.port = kwargs.get('port', None)
self.disable_trace_route = kwargs.get('disable_trace_route', None)
class ConnectionMonitorTestConfiguration(msrest.serialization.Model):
"""Describes a connection monitor test configuration.
All required parameters must be populated in order to send to Azure.
:param name: Required. The name of the connection monitor test configuration.
:type name: str
:param test_frequency_sec: The frequency of test evaluation, in seconds.
:type test_frequency_sec: int
:param protocol: Required. The protocol to use in test evaluation. Possible values include:
"Tcp", "Http", "Icmp".
:type protocol: str or
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTestConfigurationProtocol
:param preferred_ip_version: The preferred IP version to use in test evaluation. The connection
monitor may choose to use a different version depending on other parameters. Possible values
include: "IPv4", "IPv6".
:type preferred_ip_version: str or ~azure.mgmt.network.v2020_04_01.models.PreferredIPVersion
:param http_configuration: The parameters used to perform test evaluation over HTTP.
:type http_configuration:
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorHttpConfiguration
:param tcp_configuration: The parameters used to perform test evaluation over TCP.
:type tcp_configuration:
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorTcpConfiguration
:param icmp_configuration: The parameters used to perform test evaluation over ICMP.
:type icmp_configuration:
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorIcmpConfiguration
:param success_threshold: The threshold for declaring a test successful.
:type success_threshold:
~azure.mgmt.network.v2020_04_01.models.ConnectionMonitorSuccessThreshold
"""
_validation = {
'name': {'required': True},
'protocol': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'test_frequency_sec': {'key': 'testFrequencySec', 'type': 'int'},
'protocol': {'key': 'protocol', 'type': 'str'},
'preferred_ip_version': {'key': 'preferredIPVersion', 'type': 'str'},
'http_configuration': {'key': 'httpConfiguration', 'type': 'ConnectionMonitorHttpConfiguration'},
'tcp_configuration': {'key': 'tcpConfiguration', 'type': 'ConnectionMonitorTcpConfiguration'},
'icmp_configuration': {'key': 'icmpConfiguration', 'type': 'ConnectionMonitorIcmpConfiguration'},
'success_threshold': {'key': 'successThreshold', 'type': 'ConnectionMonitorSuccessThreshold'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorTestConfiguration, self).__init__(**kwargs)
self.name = kwargs['name']
self.test_frequency_sec = kwargs.get('test_frequency_sec', None)
self.protocol = kwargs['protocol']
self.preferred_ip_version = kwargs.get('preferred_ip_version', None)
self.http_configuration = kwargs.get('http_configuration', None)
self.tcp_configuration = kwargs.get('tcp_configuration', None)
self.icmp_configuration = kwargs.get('icmp_configuration', None)
self.success_threshold = kwargs.get('success_threshold', None)
class ConnectionMonitorTestGroup(msrest.serialization.Model):
"""Describes the connection monitor test group.
All required parameters must be populated in order to send to Azure.
:param name: Required. The name of the connection monitor test group.
:type name: str
:param disable: Value indicating whether test group is disabled.
:type disable: bool
:param test_configurations: Required. List of test configuration names.
:type test_configurations: list[str]
:param sources: Required. List of source endpoint names.
:type sources: list[str]
:param destinations: Required. List of destination endpoint names.
:type destinations: list[str]
"""
_validation = {
'name': {'required': True},
'test_configurations': {'required': True},
'sources': {'required': True},
'destinations': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'disable': {'key': 'disable', 'type': 'bool'},
'test_configurations': {'key': 'testConfigurations', 'type': '[str]'},
'sources': {'key': 'sources', 'type': '[str]'},
'destinations': {'key': 'destinations', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorTestGroup, self).__init__(**kwargs)
self.name = kwargs['name']
self.disable = kwargs.get('disable', None)
self.test_configurations = kwargs['test_configurations']
self.sources = kwargs['sources']
self.destinations = kwargs['destinations']
class ConnectionMonitorWorkspaceSettings(msrest.serialization.Model):
"""Describes the settings for producing output into a log analytics workspace.
:param workspace_resource_id: Log analytics workspace resource ID.
:type workspace_resource_id: str
"""
_attribute_map = {
'workspace_resource_id': {'key': 'workspaceResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorWorkspaceSettings, self).__init__(**kwargs)
self.workspace_resource_id = kwargs.get('workspace_resource_id', None)
class ConnectionResetSharedKey(msrest.serialization.Model):
"""The virtual network connection reset shared key.
All required parameters must be populated in order to send to Azure.
:param key_length: Required. The virtual network connection reset shared key length, should
between 1 and 128.
:type key_length: int
"""
_validation = {
'key_length': {'required': True, 'maximum': 128, 'minimum': 1},
}
_attribute_map = {
'key_length': {'key': 'keyLength', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionResetSharedKey, self).__init__(**kwargs)
self.key_length = kwargs['key_length']
class ConnectionSharedKey(SubResource):
"""Response for GetConnectionSharedKey API service call.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:param value: Required. The virtual network connection shared key value.
:type value: str
"""
_validation = {
'value': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionSharedKey, self).__init__(**kwargs)
self.value = kwargs['value']
class ConnectionStateSnapshot(msrest.serialization.Model):
"""Connection state snapshot.
Variables are only populated by the server, and will be ignored when sending a request.
:param connection_state: The connection state. Possible values include: "Reachable",
"Unreachable", "Unknown".
:type connection_state: str or ~azure.mgmt.network.v2020_04_01.models.ConnectionState
:param start_time: The start time of the connection snapshot.
:type start_time: ~datetime.datetime
:param end_time: The end time of the connection snapshot.
:type end_time: ~datetime.datetime
:param evaluation_state: Connectivity analysis evaluation state. Possible values include:
"NotStarted", "InProgress", "Completed".
:type evaluation_state: str or ~azure.mgmt.network.v2020_04_01.models.EvaluationState
:param avg_latency_in_ms: Average latency in ms.
:type avg_latency_in_ms: int
:param min_latency_in_ms: Minimum latency in ms.
:type min_latency_in_ms: int
:param max_latency_in_ms: Maximum latency in ms.
:type max_latency_in_ms: int
:param probes_sent: The number of sent probes.
:type probes_sent: int
:param probes_failed: The number of failed probes.
:type probes_failed: int
:ivar hops: List of hops between the source and the destination.
:vartype hops: list[~azure.mgmt.network.v2020_04_01.models.ConnectivityHop]
"""
_validation = {
'hops': {'readonly': True},
}
_attribute_map = {
'connection_state': {'key': 'connectionState', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'evaluation_state': {'key': 'evaluationState', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionStateSnapshot, self).__init__(**kwargs)
self.connection_state = kwargs.get('connection_state', None)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
self.evaluation_state = kwargs.get('evaluation_state', None)
self.avg_latency_in_ms = kwargs.get('avg_latency_in_ms', None)
self.min_latency_in_ms = kwargs.get('min_latency_in_ms', None)
self.max_latency_in_ms = kwargs.get('max_latency_in_ms', None)
self.probes_sent = kwargs.get('probes_sent', None)
self.probes_failed = kwargs.get('probes_failed', None)
self.hops = None
class ConnectivityDestination(msrest.serialization.Model):
"""Parameters that define destination of connection.
:param resource_id: The ID of the resource to which a connection attempt will be made.
:type resource_id: str
:param address: The IP address or URI the resource to which a connection attempt will be made.
:type address: str
:param port: Port on which check connectivity will be performed.
:type port: int
"""
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityDestination, self).__init__(**kwargs)
self.resource_id = kwargs.get('resource_id', None)
self.address = kwargs.get('address', None)
self.port = kwargs.get('port', None)
class ConnectivityHop(msrest.serialization.Model):
"""Information about a hop between the source and the destination.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The type of the hop.
:vartype type: str
:ivar id: The ID of the hop.
:vartype id: str
:ivar address: The IP address of the hop.
:vartype address: str
:ivar resource_id: The ID of the resource corresponding to this hop.
:vartype resource_id: str
:ivar next_hop_ids: List of next hop identifiers.
:vartype next_hop_ids: list[str]
:ivar issues: List of issues.
:vartype issues: list[~azure.mgmt.network.v2020_04_01.models.ConnectivityIssue]
"""
_validation = {
'type': {'readonly': True},
'id': {'readonly': True},
'address': {'readonly': True},
'resource_id': {'readonly': True},
'next_hop_ids': {'readonly': True},
'issues': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'next_hop_ids': {'key': 'nextHopIds', 'type': '[str]'},
'issues': {'key': 'issues', 'type': '[ConnectivityIssue]'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityHop, self).__init__(**kwargs)
self.type = None
self.id = None
self.address = None
self.resource_id = None
self.next_hop_ids = None
self.issues = None
class ConnectivityInformation(msrest.serialization.Model):
"""Information on the connectivity status.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar hops: List of hops between the source and the destination.
:vartype hops: list[~azure.mgmt.network.v2020_04_01.models.ConnectivityHop]
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connected", "Disconnected", "Degraded".
:vartype connection_status: str or ~azure.mgmt.network.v2020_04_01.models.ConnectionStatus
:ivar avg_latency_in_ms: Average latency in milliseconds.
:vartype avg_latency_in_ms: int
:ivar min_latency_in_ms: Minimum latency in milliseconds.
:vartype min_latency_in_ms: int
:ivar max_latency_in_ms: Maximum latency in milliseconds.
:vartype max_latency_in_ms: int
:ivar probes_sent: Total number of probes sent.
:vartype probes_sent: int
:ivar probes_failed: Number of failed probes.
:vartype probes_failed: int
"""
_validation = {
'hops': {'readonly': True},
'connection_status': {'readonly': True},
'avg_latency_in_ms': {'readonly': True},
'min_latency_in_ms': {'readonly': True},
'max_latency_in_ms': {'readonly': True},
'probes_sent': {'readonly': True},
'probes_failed': {'readonly': True},
}
_attribute_map = {
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityInformation, self).__init__(**kwargs)
self.hops = None
self.connection_status = None
self.avg_latency_in_ms = None
self.min_latency_in_ms = None
self.max_latency_in_ms = None
self.probes_sent = None
self.probes_failed = None
class ConnectivityIssue(msrest.serialization.Model):
"""Information about an issue encountered in the process of checking for connectivity.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar origin: The origin of the issue. Possible values include: "Local", "Inbound", "Outbound".
:vartype origin: str or ~azure.mgmt.network.v2020_04_01.models.Origin
:ivar severity: The severity of the issue. Possible values include: "Error", "Warning".
:vartype severity: str or ~azure.mgmt.network.v2020_04_01.models.Severity
:ivar type: The type of issue. Possible values include: "Unknown", "AgentStopped",
"GuestFirewall", "DnsResolution", "SocketBind", "NetworkSecurityRule", "UserDefinedRoute",
"PortThrottled", "Platform".
:vartype type: str or ~azure.mgmt.network.v2020_04_01.models.IssueType
:ivar context: Provides additional context on the issue.
:vartype context: list[dict[str, str]]
"""
_validation = {
'origin': {'readonly': True},
'severity': {'readonly': True},
'type': {'readonly': True},
'context': {'readonly': True},
}
_attribute_map = {
'origin': {'key': 'origin', 'type': 'str'},
'severity': {'key': 'severity', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'context': {'key': 'context', 'type': '[{str}]'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityIssue, self).__init__(**kwargs)
self.origin = None
self.severity = None
self.type = None
self.context = None
class ConnectivityParameters(msrest.serialization.Model):
"""Parameters that determine how the connectivity check will be performed.
All required parameters must be populated in order to send to Azure.
:param source: Required. The source of the connection.
:type source: ~azure.mgmt.network.v2020_04_01.models.ConnectivitySource
:param destination: Required. The destination of connection.
:type destination: ~azure.mgmt.network.v2020_04_01.models.ConnectivityDestination
:param protocol: Network protocol. Possible values include: "Tcp", "Http", "Https", "Icmp".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.Protocol
:param protocol_configuration: Configuration of the protocol.
:type protocol_configuration: ~azure.mgmt.network.v2020_04_01.models.ProtocolConfiguration
:param preferred_ip_version: Preferred IP version of the connection. Possible values include:
"IPv4", "IPv6".
:type preferred_ip_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectivitySource'},
'destination': {'key': 'destination', 'type': 'ConnectivityDestination'},
'protocol': {'key': 'protocol', 'type': 'str'},
'protocol_configuration': {'key': 'protocolConfiguration', 'type': 'ProtocolConfiguration'},
'preferred_ip_version': {'key': 'preferredIPVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityParameters, self).__init__(**kwargs)
self.source = kwargs['source']
self.destination = kwargs['destination']
self.protocol = kwargs.get('protocol', None)
self.protocol_configuration = kwargs.get('protocol_configuration', None)
self.preferred_ip_version = kwargs.get('preferred_ip_version', None)
class ConnectivitySource(msrest.serialization.Model):
"""Parameters that define the source of the connection.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource from which a connectivity check will be
initiated.
:type resource_id: str
:param port: The source port from which a connectivity check will be performed.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = kwargs['resource_id']
self.port = kwargs.get('port', None)
class Container(SubResource):
"""Reference to container resource in remote resource provider.
:param id: Resource ID.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Container, self).__init__(**kwargs)
class ContainerNetworkInterface(SubResource):
"""Container network interface child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar container_network_interface_configuration: Container network interface configuration from
which this container network interface is created.
:vartype container_network_interface_configuration:
~azure.mgmt.network.v2020_04_01.models.ContainerNetworkInterfaceConfiguration
:param container: Reference to the container to which this container network interface is
attached.
:type container: ~azure.mgmt.network.v2020_04_01.models.Container
:ivar ip_configurations: Reference to the ip configuration on this container nic.
:vartype ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ContainerNetworkInterfaceIpConfiguration]
:ivar provisioning_state: The provisioning state of the container network interface resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'container_network_interface_configuration': {'readonly': True},
'ip_configurations': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'container_network_interface_configuration': {'key': 'properties.containerNetworkInterfaceConfiguration', 'type': 'ContainerNetworkInterfaceConfiguration'},
'container': {'key': 'properties.container', 'type': 'Container'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[ContainerNetworkInterfaceIpConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterface, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.container_network_interface_configuration = None
self.container = kwargs.get('container', None)
self.ip_configurations = None
self.provisioning_state = None
class ContainerNetworkInterfaceConfiguration(SubResource):
"""Container network interface configuration child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param ip_configurations: A list of ip configurations of the container network interface
configuration.
:type ip_configurations: list[~azure.mgmt.network.v2020_04_01.models.IPConfigurationProfile]
:param container_network_interfaces: A list of container network interfaces created from this
container network interface configuration.
:type container_network_interfaces: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the container network interface
configuration resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfigurationProfile]'},
'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterfaceConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.container_network_interfaces = kwargs.get('container_network_interfaces', None)
self.provisioning_state = None
class ContainerNetworkInterfaceIpConfiguration(msrest.serialization.Model):
"""The ip configuration for a container network interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the container network interface IP
configuration resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterfaceIpConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.provisioning_state = None
class CustomDnsConfigPropertiesFormat(msrest.serialization.Model):
"""Contains custom Dns resolution configuration from customer.
:param fqdn: Fqdn that resolves to private endpoint ip address.
:type fqdn: str
:param ip_addresses: A list of private ip addresses of the private endpoint.
:type ip_addresses: list[str]
"""
_attribute_map = {
'fqdn': {'key': 'fqdn', 'type': 'str'},
'ip_addresses': {'key': 'ipAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(CustomDnsConfigPropertiesFormat, self).__init__(**kwargs)
self.fqdn = kwargs.get('fqdn', None)
self.ip_addresses = kwargs.get('ip_addresses', None)
class DdosCustomPolicy(Resource):
"""A DDoS custom policy in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the DDoS custom policy resource. It uniquely
identifies the resource, even if the user changes its name or migrate the resource across
subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the DDoS custom policy resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar public_ip_addresses: The list of public IPs associated with the DDoS custom policy
resource. This list is read-only.
:vartype public_ip_addresses: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param protocol_custom_settings: The protocol-specific DDoS policy customization parameters.
:type protocol_custom_settings:
list[~azure.mgmt.network.v2020_04_01.models.ProtocolCustomSettingsFormat]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
'public_ip_addresses': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[SubResource]'},
'protocol_custom_settings': {'key': 'properties.protocolCustomSettings', 'type': '[ProtocolCustomSettingsFormat]'},
}
def __init__(
self,
**kwargs
):
super(DdosCustomPolicy, self).__init__(**kwargs)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
self.public_ip_addresses = None
self.protocol_custom_settings = kwargs.get('protocol_custom_settings', None)
class DdosProtectionPlan(msrest.serialization.Model):
"""A DDoS protection plan in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource ID.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the DDoS protection plan resource. It
uniquely identifies the resource, even if the user changes its name or migrate the resource
across subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the DDoS protection plan resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar virtual_networks: The list of virtual networks associated with the DDoS protection plan
resource. This list is read-only.
:vartype virtual_networks: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
'virtual_networks': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'virtual_networks': {'key': 'properties.virtualNetworks', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(DdosProtectionPlan, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
self.virtual_networks = None
class DdosProtectionPlanListResult(msrest.serialization.Model):
"""A list of DDoS protection plans.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of DDoS protection plans.
:type value: list[~azure.mgmt.network.v2020_04_01.models.DdosProtectionPlan]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[DdosProtectionPlan]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DdosProtectionPlanListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class DdosSettings(msrest.serialization.Model):
"""Contains the DDoS protection settings of the public IP.
:param ddos_custom_policy: The DDoS custom policy associated with the public IP.
:type ddos_custom_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param protection_coverage: The DDoS protection policy customizability of the public IP. Only
standard coverage will have the ability to be customized. Possible values include: "Basic",
"Standard".
:type protection_coverage: str or
~azure.mgmt.network.v2020_04_01.models.DdosSettingsProtectionCoverage
:param protected_ip: Enables DDoS protection on the public IP.
:type protected_ip: bool
"""
_attribute_map = {
'ddos_custom_policy': {'key': 'ddosCustomPolicy', 'type': 'SubResource'},
'protection_coverage': {'key': 'protectionCoverage', 'type': 'str'},
'protected_ip': {'key': 'protectedIP', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(DdosSettings, self).__init__(**kwargs)
self.ddos_custom_policy = kwargs.get('ddos_custom_policy', None)
self.protection_coverage = kwargs.get('protection_coverage', None)
self.protected_ip = kwargs.get('protected_ip', None)
class Delegation(SubResource):
"""Details the service to which the subnet is delegated.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a subnet. This name can be used to
access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param service_name: The name of the service to whom the subnet should be delegated (e.g.
Microsoft.Sql/servers).
:type service_name: str
:ivar actions: The actions permitted to the service upon delegation.
:vartype actions: list[str]
:ivar provisioning_state: The provisioning state of the service delegation resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'actions': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'service_name': {'key': 'properties.serviceName', 'type': 'str'},
'actions': {'key': 'properties.actions', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Delegation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.service_name = kwargs.get('service_name', None)
self.actions = None
self.provisioning_state = None
class DeviceProperties(msrest.serialization.Model):
"""List of properties of the device.
:param device_vendor: Name of the device Vendor.
:type device_vendor: str
:param device_model: Model of the device.
:type device_model: str
:param link_speed_in_mbps: Link speed.
:type link_speed_in_mbps: int
"""
_attribute_map = {
'device_vendor': {'key': 'deviceVendor', 'type': 'str'},
'device_model': {'key': 'deviceModel', 'type': 'str'},
'link_speed_in_mbps': {'key': 'linkSpeedInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(DeviceProperties, self).__init__(**kwargs)
self.device_vendor = kwargs.get('device_vendor', None)
self.device_model = kwargs.get('device_model', None)
self.link_speed_in_mbps = kwargs.get('link_speed_in_mbps', None)
class DhcpOptions(msrest.serialization.Model):
"""DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for a subnet overrides VNET DHCP options.
:param dns_servers: The list of DNS servers IP addresses.
:type dns_servers: list[str]
"""
_attribute_map = {
'dns_servers': {'key': 'dnsServers', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(DhcpOptions, self).__init__(**kwargs)
self.dns_servers = kwargs.get('dns_servers', None)
class Dimension(msrest.serialization.Model):
"""Dimension of the metric.
:param name: The name of the dimension.
:type name: str
:param display_name: The display name of the dimension.
:type display_name: str
:param internal_name: The internal name of the dimension.
:type internal_name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'internal_name': {'key': 'internalName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Dimension, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.internal_name = kwargs.get('internal_name', None)
class DnsNameAvailabilityResult(msrest.serialization.Model):
"""Response for the CheckDnsNameAvailability API service call.
:param available: Domain availability (True/False).
:type available: bool
"""
_attribute_map = {
'available': {'key': 'available', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(DnsNameAvailabilityResult, self).__init__(**kwargs)
self.available = kwargs.get('available', None)
class EffectiveNetworkSecurityGroup(msrest.serialization.Model):
"""Effective network security group.
:param network_security_group: The ID of network security group that is applied.
:type network_security_group: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param association: Associated resources.
:type association:
~azure.mgmt.network.v2020_04_01.models.EffectiveNetworkSecurityGroupAssociation
:param effective_security_rules: A collection of effective security rules.
:type effective_security_rules:
list[~azure.mgmt.network.v2020_04_01.models.EffectiveNetworkSecurityRule]
:param tag_map: Mapping of tags to list of IP Addresses included within the tag.
:type tag_map: str
"""
_attribute_map = {
'network_security_group': {'key': 'networkSecurityGroup', 'type': 'SubResource'},
'association': {'key': 'association', 'type': 'EffectiveNetworkSecurityGroupAssociation'},
'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'},
'tag_map': {'key': 'tagMap', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroup, self).__init__(**kwargs)
self.network_security_group = kwargs.get('network_security_group', None)
self.association = kwargs.get('association', None)
self.effective_security_rules = kwargs.get('effective_security_rules', None)
self.tag_map = kwargs.get('tag_map', None)
class EffectiveNetworkSecurityGroupAssociation(msrest.serialization.Model):
"""The effective network security group association.
:param subnet: The ID of the subnet if assigned.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param network_interface: The ID of the network interface if assigned.
:type network_interface: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_attribute_map = {
'subnet': {'key': 'subnet', 'type': 'SubResource'},
'network_interface': {'key': 'networkInterface', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroupAssociation, self).__init__(**kwargs)
self.subnet = kwargs.get('subnet', None)
self.network_interface = kwargs.get('network_interface', None)
class EffectiveNetworkSecurityGroupListResult(msrest.serialization.Model):
"""Response for list effective network security groups API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of effective network security groups.
:type value: list[~azure.mgmt.network.v2020_04_01.models.EffectiveNetworkSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[EffectiveNetworkSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class EffectiveNetworkSecurityRule(msrest.serialization.Model):
"""Effective network security rules.
:param name: The name of the security rule specified by the user (if created by the user).
:type name: str
:param protocol: The network protocol this rule applies to. Possible values include: "Tcp",
"Udp", "All".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.EffectiveSecurityRuleProtocol
:param source_port_range: The source port or range.
:type source_port_range: str
:param destination_port_range: The destination port or range.
:type destination_port_range: str
:param source_port_ranges: The source port ranges. Expected values include a single integer
between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*).
:type source_port_ranges: list[str]
:param destination_port_ranges: The destination port ranges. Expected values include a single
integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*).
:type destination_port_ranges: list[str]
:param source_address_prefix: The source address prefix.
:type source_address_prefix: str
:param destination_address_prefix: The destination address prefix.
:type destination_address_prefix: str
:param source_address_prefixes: The source address prefixes. Expected values include CIDR IP
ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the
asterisk (*).
:type source_address_prefixes: list[str]
:param destination_address_prefixes: The destination address prefixes. Expected values include
CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and
the asterisk (*).
:type destination_address_prefixes: list[str]
:param expanded_source_address_prefix: The expanded source address prefix.
:type expanded_source_address_prefix: list[str]
:param expanded_destination_address_prefix: Expanded destination address prefix.
:type expanded_destination_address_prefix: list[str]
:param access: Whether network traffic is allowed or denied. Possible values include: "Allow",
"Deny".
:type access: str or ~azure.mgmt.network.v2020_04_01.models.SecurityRuleAccess
:param priority: The priority of the rule.
:type priority: int
:param direction: The direction of the rule. Possible values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2020_04_01.models.SecurityRuleDirection
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'source_port_range': {'key': 'sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'destinationPortRange', 'type': 'str'},
'source_port_ranges': {'key': 'sourcePortRanges', 'type': '[str]'},
'destination_port_ranges': {'key': 'destinationPortRanges', 'type': '[str]'},
'source_address_prefix': {'key': 'sourceAddressPrefix', 'type': 'str'},
'destination_address_prefix': {'key': 'destinationAddressPrefix', 'type': 'str'},
'source_address_prefixes': {'key': 'sourceAddressPrefixes', 'type': '[str]'},
'destination_address_prefixes': {'key': 'destinationAddressPrefixes', 'type': '[str]'},
'expanded_source_address_prefix': {'key': 'expandedSourceAddressPrefix', 'type': '[str]'},
'expanded_destination_address_prefix': {'key': 'expandedDestinationAddressPrefix', 'type': '[str]'},
'access': {'key': 'access', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'direction': {'key': 'direction', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.protocol = kwargs.get('protocol', None)
self.source_port_range = kwargs.get('source_port_range', None)
self.destination_port_range = kwargs.get('destination_port_range', None)
self.source_port_ranges = kwargs.get('source_port_ranges', None)
self.destination_port_ranges = kwargs.get('destination_port_ranges', None)
self.source_address_prefix = kwargs.get('source_address_prefix', None)
self.destination_address_prefix = kwargs.get('destination_address_prefix', None)
self.source_address_prefixes = kwargs.get('source_address_prefixes', None)
self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None)
self.expanded_source_address_prefix = kwargs.get('expanded_source_address_prefix', None)
self.expanded_destination_address_prefix = kwargs.get('expanded_destination_address_prefix', None)
self.access = kwargs.get('access', None)
self.priority = kwargs.get('priority', None)
self.direction = kwargs.get('direction', None)
class EffectiveRoute(msrest.serialization.Model):
"""Effective Route.
:param name: The name of the user defined route. This is optional.
:type name: str
:param disable_bgp_route_propagation: If true, on-premises routes are not propagated to the
network interfaces in the subnet.
:type disable_bgp_route_propagation: bool
:param source: Who created the route. Possible values include: "Unknown", "User",
"VirtualNetworkGateway", "Default".
:type source: str or ~azure.mgmt.network.v2020_04_01.models.EffectiveRouteSource
:param state: The value of effective route. Possible values include: "Active", "Invalid".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.EffectiveRouteState
:param address_prefix: The address prefixes of the effective routes in CIDR notation.
:type address_prefix: list[str]
:param next_hop_ip_address: The IP address of the next hop of the effective route.
:type next_hop_ip_address: list[str]
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values
include: "VirtualNetworkGateway", "VnetLocal", "Internet", "VirtualAppliance", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2020_04_01.models.RouteNextHopType
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'disable_bgp_route_propagation': {'key': 'disableBgpRoutePropagation', 'type': 'bool'},
'source': {'key': 'source', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'address_prefix': {'key': 'addressPrefix', 'type': '[str]'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': '[str]'},
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveRoute, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None)
self.source = kwargs.get('source', None)
self.state = kwargs.get('state', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.next_hop_type = kwargs.get('next_hop_type', None)
class EffectiveRouteListResult(msrest.serialization.Model):
"""Response for list effective route API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of effective routes.
:type value: list[~azure.mgmt.network.v2020_04_01.models.EffectiveRoute]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[EffectiveRoute]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveRouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class EndpointServiceResult(SubResource):
"""Endpoint service.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Name of the endpoint service.
:vartype name: str
:ivar type: Type of the endpoint service.
:vartype type: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EndpointServiceResult, self).__init__(**kwargs)
self.name = None
self.type = None
class EndpointServicesListResult(msrest.serialization.Model):
"""Response for the ListAvailableEndpointServices API service call.
:param value: List of available endpoint services in a region.
:type value: list[~azure.mgmt.network.v2020_04_01.models.EndpointServiceResult]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[EndpointServiceResult]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EndpointServicesListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class Error(msrest.serialization.Model):
"""Common error representation.
:param code: Error code.
:type code: str
:param message: Error message.
:type message: str
:param target: Error target.
:type target: str
:param details: Error details.
:type details: list[~azure.mgmt.network.v2020_04_01.models.ErrorDetails]
:param inner_error: Inner error message.
:type inner_error: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[ErrorDetails]'},
'inner_error': {'key': 'innerError', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Error, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.message = kwargs.get('message', None)
self.target = kwargs.get('target', None)
self.details = kwargs.get('details', None)
self.inner_error = kwargs.get('inner_error', None)
class ErrorDetails(msrest.serialization.Model):
"""Common error details representation.
:param code: Error code.
:type code: str
:param target: Error target.
:type target: str
:param message: Error message.
:type message: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ErrorDetails, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.target = kwargs.get('target', None)
self.message = kwargs.get('message', None)
class ErrorResponse(msrest.serialization.Model):
"""The error object.
:param error: The error details object.
:type error: ~azure.mgmt.network.v2020_04_01.models.ErrorDetails
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorDetails'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponse, self).__init__(**kwargs)
self.error = kwargs.get('error', None)
class EvaluatedNetworkSecurityGroup(msrest.serialization.Model):
"""Results of network security group evaluation.
Variables are only populated by the server, and will be ignored when sending a request.
:param network_security_group_id: Network security group ID.
:type network_security_group_id: str
:param applied_to: Resource ID of nic or subnet to which network security group is applied.
:type applied_to: str
:param matched_rule: Matched network security rule.
:type matched_rule: ~azure.mgmt.network.v2020_04_01.models.MatchedRule
:ivar rules_evaluation_result: List of network security rules evaluation results.
:vartype rules_evaluation_result:
list[~azure.mgmt.network.v2020_04_01.models.NetworkSecurityRulesEvaluationResult]
"""
_validation = {
'rules_evaluation_result': {'readonly': True},
}
_attribute_map = {
'network_security_group_id': {'key': 'networkSecurityGroupId', 'type': 'str'},
'applied_to': {'key': 'appliedTo', 'type': 'str'},
'matched_rule': {'key': 'matchedRule', 'type': 'MatchedRule'},
'rules_evaluation_result': {'key': 'rulesEvaluationResult', 'type': '[NetworkSecurityRulesEvaluationResult]'},
}
def __init__(
self,
**kwargs
):
super(EvaluatedNetworkSecurityGroup, self).__init__(**kwargs)
self.network_security_group_id = kwargs.get('network_security_group_id', None)
self.applied_to = kwargs.get('applied_to', None)
self.matched_rule = kwargs.get('matched_rule', None)
self.rules_evaluation_result = None
class ExpressRouteCircuit(Resource):
"""ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitSku
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param allow_classic_operations: Allow classic operations.
:type allow_classic_operations: bool
:param circuit_provisioning_state: The CircuitProvisioningState state of the resource.
:type circuit_provisioning_state: str
:param service_provider_provisioning_state: The ServiceProviderProvisioningState state of the
resource. Possible values include: "NotProvisioned", "Provisioning", "Provisioned",
"Deprovisioning".
:type service_provider_provisioning_state: str or
~azure.mgmt.network.v2020_04_01.models.ServiceProviderProvisioningState
:param authorizations: The list of authorizations.
:type authorizations:
list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitAuthorization]
:param peerings: The list of peerings.
:type peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:param service_key: The ServiceKey.
:type service_key: str
:param service_provider_notes: The ServiceProviderNotes.
:type service_provider_notes: str
:param service_provider_properties: The ServiceProviderProperties.
:type service_provider_properties:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitServiceProviderProperties
:param express_route_port: The reference to the ExpressRoutePort resource when the circuit is
provisioned on an ExpressRoutePort resource.
:type express_route_port: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param bandwidth_in_gbps: The bandwidth of the circuit when the circuit is provisioned on an
ExpressRoutePort resource.
:type bandwidth_in_gbps: float
:ivar stag: The identifier of the circuit traffic. Outer tag for QinQ encapsulation.
:vartype stag: int
:ivar provisioning_state: The provisioning state of the express route circuit resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:param global_reach_enabled: Flag denoting global reach status.
:type global_reach_enabled: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'stag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'ExpressRouteCircuitSku'},
'etag': {'key': 'etag', 'type': 'str'},
'allow_classic_operations': {'key': 'properties.allowClassicOperations', 'type': 'bool'},
'circuit_provisioning_state': {'key': 'properties.circuitProvisioningState', 'type': 'str'},
'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'},
'authorizations': {'key': 'properties.authorizations', 'type': '[ExpressRouteCircuitAuthorization]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'service_key': {'key': 'properties.serviceKey', 'type': 'str'},
'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'},
'service_provider_properties': {'key': 'properties.serviceProviderProperties', 'type': 'ExpressRouteCircuitServiceProviderProperties'},
'express_route_port': {'key': 'properties.expressRoutePort', 'type': 'SubResource'},
'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'float'},
'stag': {'key': 'properties.stag', 'type': 'int'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'global_reach_enabled': {'key': 'properties.globalReachEnabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuit, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = None
self.allow_classic_operations = kwargs.get('allow_classic_operations', None)
self.circuit_provisioning_state = kwargs.get('circuit_provisioning_state', None)
self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None)
self.authorizations = kwargs.get('authorizations', None)
self.peerings = kwargs.get('peerings', None)
self.service_key = kwargs.get('service_key', None)
self.service_provider_notes = kwargs.get('service_provider_notes', None)
self.service_provider_properties = kwargs.get('service_provider_properties', None)
self.express_route_port = kwargs.get('express_route_port', None)
self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None)
self.stag = None
self.provisioning_state = None
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.global_reach_enabled = kwargs.get('global_reach_enabled', None)
class ExpressRouteCircuitArpTable(msrest.serialization.Model):
"""The ARP table associated with the ExpressRouteCircuit.
:param age: Entry age in minutes.
:type age: int
:param interface: Interface address.
:type interface: str
:param ip_address: The IP address.
:type ip_address: str
:param mac_address: The MAC address.
:type mac_address: str
"""
_attribute_map = {
'age': {'key': 'age', 'type': 'int'},
'interface': {'key': 'interface', 'type': 'str'},
'ip_address': {'key': 'ipAddress', 'type': 'str'},
'mac_address': {'key': 'macAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitArpTable, self).__init__(**kwargs)
self.age = kwargs.get('age', None)
self.interface = kwargs.get('interface', None)
self.ip_address = kwargs.get('ip_address', None)
self.mac_address = kwargs.get('mac_address', None)
class ExpressRouteCircuitAuthorization(SubResource):
"""Authorization in an ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param authorization_key: The authorization key.
:type authorization_key: str
:param authorization_use_status: The authorization use status. Possible values include:
"Available", "InUse".
:type authorization_use_status: str or
~azure.mgmt.network.v2020_04_01.models.AuthorizationUseStatus
:ivar provisioning_state: The provisioning state of the authorization resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'authorization_use_status': {'key': 'properties.authorizationUseStatus', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitAuthorization, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.authorization_key = kwargs.get('authorization_key', None)
self.authorization_use_status = kwargs.get('authorization_use_status', None)
self.provisioning_state = None
class ExpressRouteCircuitConnection(SubResource):
"""Express Route Circuit Connection in an ExpressRouteCircuitPeering resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the circuit initiating connection.
:type express_route_circuit_peering: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the peered circuit.
:type peer_express_route_circuit_peering: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param address_prefix: /29 IP address space to carve out Customer addresses for tunnels.
:type address_prefix: str
:param authorization_key: The authorization key.
:type authorization_key: str
:param ipv6_circuit_connection_config: IPv6 Address PrefixProperties of the express route
circuit connection.
:type ipv6_circuit_connection_config:
~azure.mgmt.network.v2020_04_01.models.Ipv6CircuitConnectionConfig
:ivar circuit_connection_status: Express Route Circuit connection state. Possible values
include: "Connected", "Connecting", "Disconnected".
:vartype circuit_connection_status: str or
~azure.mgmt.network.v2020_04_01.models.CircuitConnectionStatus
:ivar provisioning_state: The provisioning state of the express route circuit connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'circuit_connection_status': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'},
'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'ipv6_circuit_connection_config': {'key': 'properties.ipv6CircuitConnectionConfig', 'type': 'Ipv6CircuitConnectionConfig'},
'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.ipv6_circuit_connection_config = kwargs.get('ipv6_circuit_connection_config', None)
self.circuit_connection_status = None
self.provisioning_state = None
class ExpressRouteCircuitConnectionListResult(msrest.serialization.Model):
"""Response for ListConnections API service call retrieves all global reach connections that belongs to a Private Peering for an ExpressRouteCircuit.
:param value: The global reach connection associated with Private Peering in an ExpressRoute
Circuit.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitConnection]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitListResult(msrest.serialization.Model):
"""Response for ListExpressRouteCircuit API service call.
:param value: A list of ExpressRouteCircuits in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuit]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuit]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitPeering(SubResource):
"""Peering in an ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param peering_type: The peering type. Possible values include: "AzurePublicPeering",
"AzurePrivatePeering", "MicrosoftPeering".
:type peering_type: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRoutePeeringType
:param state: The peering state. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRoutePeeringState
:param azure_asn: The Azure ASN.
:type azure_asn: int
:param peer_asn: The peer ASN.
:type peer_asn: long
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:param primary_azure_port: The primary port.
:type primary_azure_port: str
:param secondary_azure_port: The secondary port.
:type secondary_azure_port: str
:param shared_key: The shared key.
:type shared_key: str
:param vlan_id: The VLAN ID.
:type vlan_id: int
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringConfig
:param stats: The peering stats of express route circuit.
:type stats: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitStats
:ivar provisioning_state: The provisioning state of the express route circuit peering resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:ivar last_modified_by: Who was the last to modify the peering.
:vartype last_modified_by: str
:param route_filter: The reference to the RouteFilter resource.
:type route_filter: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param ipv6_peering_config: The IPv6 peering configuration.
:type ipv6_peering_config:
~azure.mgmt.network.v2020_04_01.models.Ipv6ExpressRouteCircuitPeeringConfig
:param express_route_connection: The ExpressRoute connection.
:type express_route_connection: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteConnectionId
:param connections: The list of circuit connections associated with Azure Private Peering for
this circuit.
:type connections: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitConnection]
:ivar peered_connections: The list of peered circuit connections associated with Azure Private
Peering for this circuit.
:vartype peered_connections:
list[~azure.mgmt.network.v2020_04_01.models.PeerExpressRouteCircuitConnection]
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'peer_asn': {'maximum': 4294967295, 'minimum': 1},
'provisioning_state': {'readonly': True},
'last_modified_by': {'readonly': True},
'peered_connections': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'peering_type': {'key': 'properties.peeringType', 'type': 'str'},
'state': {'key': 'properties.state', 'type': 'str'},
'azure_asn': {'key': 'properties.azureASN', 'type': 'int'},
'peer_asn': {'key': 'properties.peerASN', 'type': 'long'},
'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'vlan_id': {'key': 'properties.vlanId', 'type': 'int'},
'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'stats': {'key': 'properties.stats', 'type': 'ExpressRouteCircuitStats'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'},
'route_filter': {'key': 'properties.routeFilter', 'type': 'SubResource'},
'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'},
'express_route_connection': {'key': 'properties.expressRouteConnection', 'type': 'ExpressRouteConnectionId'},
'connections': {'key': 'properties.connections', 'type': '[ExpressRouteCircuitConnection]'},
'peered_connections': {'key': 'properties.peeredConnections', 'type': '[PeerExpressRouteCircuitConnection]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.peering_type = kwargs.get('peering_type', None)
self.state = kwargs.get('state', None)
self.azure_asn = kwargs.get('azure_asn', None)
self.peer_asn = kwargs.get('peer_asn', None)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.primary_azure_port = kwargs.get('primary_azure_port', None)
self.secondary_azure_port = kwargs.get('secondary_azure_port', None)
self.shared_key = kwargs.get('shared_key', None)
self.vlan_id = kwargs.get('vlan_id', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.stats = kwargs.get('stats', None)
self.provisioning_state = None
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.last_modified_by = None
self.route_filter = kwargs.get('route_filter', None)
self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None)
self.express_route_connection = kwargs.get('express_route_connection', None)
self.connections = kwargs.get('connections', None)
self.peered_connections = None
class ExpressRouteCircuitPeeringConfig(msrest.serialization.Model):
"""Specifies the peering configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:param advertised_public_prefixes: The reference to AdvertisedPublicPrefixes.
:type advertised_public_prefixes: list[str]
:param advertised_communities: The communities of bgp peering. Specified for microsoft peering.
:type advertised_communities: list[str]
:ivar advertised_public_prefixes_state: The advertised public prefix state of the Peering
resource. Possible values include: "NotConfigured", "Configuring", "Configured",
"ValidationNeeded".
:vartype advertised_public_prefixes_state: str or
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringAdvertisedPublicPrefixState
:param legacy_mode: The legacy mode of the peering.
:type legacy_mode: int
:param customer_asn: The CustomerASN of the peering.
:type customer_asn: int
:param routing_registry_name: The RoutingRegistryName of the configuration.
:type routing_registry_name: str
"""
_validation = {
'advertised_public_prefixes_state': {'readonly': True},
}
_attribute_map = {
'advertised_public_prefixes': {'key': 'advertisedPublicPrefixes', 'type': '[str]'},
'advertised_communities': {'key': 'advertisedCommunities', 'type': '[str]'},
'advertised_public_prefixes_state': {'key': 'advertisedPublicPrefixesState', 'type': 'str'},
'legacy_mode': {'key': 'legacyMode', 'type': 'int'},
'customer_asn': {'key': 'customerASN', 'type': 'int'},
'routing_registry_name': {'key': 'routingRegistryName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs)
self.advertised_public_prefixes = kwargs.get('advertised_public_prefixes', None)
self.advertised_communities = kwargs.get('advertised_communities', None)
self.advertised_public_prefixes_state = None
self.legacy_mode = kwargs.get('legacy_mode', None)
self.customer_asn = kwargs.get('customer_asn', None)
self.routing_registry_name = kwargs.get('routing_registry_name', None)
class ExpressRouteCircuitPeeringId(msrest.serialization.Model):
"""ExpressRoute circuit peering identifier.
:param id: The ID of the ExpressRoute circuit peering.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringId, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ExpressRouteCircuitPeeringListResult(msrest.serialization.Model):
"""Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCircuit.
:param value: The peerings in an express route circuit.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitReference(msrest.serialization.Model):
"""Reference to an express route circuit.
:param id: Corresponding Express Route Circuit Id.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitReference, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ExpressRouteCircuitRoutesTable(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param network: IP address of a network entity.
:type network: str
:param next_hop: NextHop address.
:type next_hop: str
:param loc_prf: Local preference value as set with the set local-preference route-map
configuration command.
:type loc_prf: str
:param weight: Route Weight.
:type weight: int
:param path: Autonomous system paths to the destination network.
:type path: str
"""
_attribute_map = {
'network': {'key': 'network', 'type': 'str'},
'next_hop': {'key': 'nextHop', 'type': 'str'},
'loc_prf': {'key': 'locPrf', 'type': 'str'},
'weight': {'key': 'weight', 'type': 'int'},
'path': {'key': 'path', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitRoutesTable, self).__init__(**kwargs)
self.network = kwargs.get('network', None)
self.next_hop = kwargs.get('next_hop', None)
self.loc_prf = kwargs.get('loc_prf', None)
self.weight = kwargs.get('weight', None)
self.path = kwargs.get('path', None)
class ExpressRouteCircuitRoutesTableSummary(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param neighbor: IP address of the neighbor.
:type neighbor: str
:param v: BGP version number spoken to the neighbor.
:type v: int
:param as_property: Autonomous system number.
:type as_property: int
:param up_down: The length of time that the BGP session has been in the Established state, or
the current status if not in the Established state.
:type up_down: str
:param state_pfx_rcd: Current state of the BGP session, and the number of prefixes that have
been received from a neighbor or peer group.
:type state_pfx_rcd: str
"""
_attribute_map = {
'neighbor': {'key': 'neighbor', 'type': 'str'},
'v': {'key': 'v', 'type': 'int'},
'as_property': {'key': 'as', 'type': 'int'},
'up_down': {'key': 'upDown', 'type': 'str'},
'state_pfx_rcd': {'key': 'statePfxRcd', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitRoutesTableSummary, self).__init__(**kwargs)
self.neighbor = kwargs.get('neighbor', None)
self.v = kwargs.get('v', None)
self.as_property = kwargs.get('as_property', None)
self.up_down = kwargs.get('up_down', None)
self.state_pfx_rcd = kwargs.get('state_pfx_rcd', None)
class ExpressRouteCircuitsArpTableListResult(msrest.serialization.Model):
"""Response for ListArpTable associated with the Express Route Circuits API.
:param value: A list of the ARP tables.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitArpTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitArpTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsArpTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitServiceProviderProperties(msrest.serialization.Model):
"""Contains ServiceProviderProperties in an ExpressRouteCircuit.
:param service_provider_name: The serviceProviderName.
:type service_provider_name: str
:param peering_location: The peering location.
:type peering_location: str
:param bandwidth_in_mbps: The BandwidthInMbps.
:type bandwidth_in_mbps: int
"""
_attribute_map = {
'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'},
'peering_location': {'key': 'peeringLocation', 'type': 'str'},
'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitServiceProviderProperties, self).__init__(**kwargs)
self.service_provider_name = kwargs.get('service_provider_name', None)
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None)
class ExpressRouteCircuitSku(msrest.serialization.Model):
"""Contains SKU in an ExpressRouteCircuit.
:param name: The name of the SKU.
:type name: str
:param tier: The tier of the SKU. Possible values include: "Standard", "Premium", "Basic",
"Local".
:type tier: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitSkuTier
:param family: The family of the SKU. Possible values include: "UnlimitedData", "MeteredData".
:type family: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitSkuFamily
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'family': {'key': 'family', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.family = kwargs.get('family', None)
class ExpressRouteCircuitsRoutesTableListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Circuits API.
:param value: The list of routes table.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitRoutesTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsRoutesTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitsRoutesTableSummaryListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Circuits API.
:param value: A list of the routes table.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitRoutesTableSummary]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTableSummary]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsRoutesTableSummaryListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitStats(msrest.serialization.Model):
"""Contains stats associated with the peering.
:param primarybytes_in: The Primary BytesIn of the peering.
:type primarybytes_in: long
:param primarybytes_out: The primary BytesOut of the peering.
:type primarybytes_out: long
:param secondarybytes_in: The secondary BytesIn of the peering.
:type secondarybytes_in: long
:param secondarybytes_out: The secondary BytesOut of the peering.
:type secondarybytes_out: long
"""
_attribute_map = {
'primarybytes_in': {'key': 'primarybytesIn', 'type': 'long'},
'primarybytes_out': {'key': 'primarybytesOut', 'type': 'long'},
'secondarybytes_in': {'key': 'secondarybytesIn', 'type': 'long'},
'secondarybytes_out': {'key': 'secondarybytesOut', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitStats, self).__init__(**kwargs)
self.primarybytes_in = kwargs.get('primarybytes_in', None)
self.primarybytes_out = kwargs.get('primarybytes_out', None)
self.secondarybytes_in = kwargs.get('secondarybytes_in', None)
self.secondarybytes_out = kwargs.get('secondarybytes_out', None)
class ExpressRouteConnection(SubResource):
"""ExpressRouteConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:param name: Required. The name of the resource.
:type name: str
:ivar provisioning_state: The provisioning state of the express route connection resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param express_route_circuit_peering: The ExpressRoute circuit peering.
:type express_route_circuit_peering:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringId
:param authorization_key: Authorization key to establish the connection.
:type authorization_key: str
:param routing_weight: The routing weight associated to the connection.
:type routing_weight: int
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:param routing_configuration: The Routing Configuration indicating the associated and
propagated route tables on this connection.
:type routing_configuration: ~azure.mgmt.network.v2020_04_01.models.RoutingConfiguration
"""
_validation = {
'name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'ExpressRouteCircuitPeeringId'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'},
'routing_configuration': {'key': 'properties.routingConfiguration', 'type': 'RoutingConfiguration'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnection, self).__init__(**kwargs)
self.name = kwargs['name']
self.provisioning_state = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.enable_internet_security = kwargs.get('enable_internet_security', None)
self.routing_configuration = kwargs.get('routing_configuration', None)
class ExpressRouteConnectionId(msrest.serialization.Model):
"""The ID of the ExpressRouteConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ID of the ExpressRouteConnection.
:vartype id: str
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnectionId, self).__init__(**kwargs)
self.id = None
class ExpressRouteConnectionList(msrest.serialization.Model):
"""ExpressRouteConnection list.
:param value: The list of ExpressRoute connections.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteConnection]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteConnection]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnectionList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ExpressRouteCrossConnection(Resource):
"""ExpressRouteCrossConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar primary_azure_port: The name of the primary port.
:vartype primary_azure_port: str
:ivar secondary_azure_port: The name of the secondary port.
:vartype secondary_azure_port: str
:ivar s_tag: The identifier of the circuit traffic.
:vartype s_tag: int
:param peering_location: The peering location of the ExpressRoute circuit.
:type peering_location: str
:param bandwidth_in_mbps: The circuit bandwidth In Mbps.
:type bandwidth_in_mbps: int
:param express_route_circuit: The ExpressRouteCircuit.
:type express_route_circuit:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitReference
:param service_provider_provisioning_state: The provisioning state of the circuit in the
connectivity provider system. Possible values include: "NotProvisioned", "Provisioning",
"Provisioned", "Deprovisioning".
:type service_provider_provisioning_state: str or
~azure.mgmt.network.v2020_04_01.models.ServiceProviderProvisioningState
:param service_provider_notes: Additional read only notes set by the connectivity provider.
:type service_provider_notes: str
:ivar provisioning_state: The provisioning state of the express route cross connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param peerings: The list of peerings.
:type peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionPeering]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'primary_azure_port': {'readonly': True},
'secondary_azure_port': {'readonly': True},
's_tag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
's_tag': {'key': 'properties.sTag', 'type': 'int'},
'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'},
'bandwidth_in_mbps': {'key': 'properties.bandwidthInMbps', 'type': 'int'},
'express_route_circuit': {'key': 'properties.expressRouteCircuit', 'type': 'ExpressRouteCircuitReference'},
'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'},
'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCrossConnectionPeering]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnection, self).__init__(**kwargs)
self.etag = None
self.primary_azure_port = None
self.secondary_azure_port = None
self.s_tag = None
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None)
self.express_route_circuit = kwargs.get('express_route_circuit', None)
self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None)
self.service_provider_notes = kwargs.get('service_provider_notes', None)
self.provisioning_state = None
self.peerings = kwargs.get('peerings', None)
class ExpressRouteCrossConnectionListResult(msrest.serialization.Model):
"""Response for ListExpressRouteCrossConnection API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ExpressRouteCrossConnection resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteCrossConnectionPeering(SubResource):
"""Peering in an ExpressRoute Cross Connection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param peering_type: The peering type. Possible values include: "AzurePublicPeering",
"AzurePrivatePeering", "MicrosoftPeering".
:type peering_type: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRoutePeeringType
:param state: The peering state. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRoutePeeringState
:ivar azure_asn: The Azure ASN.
:vartype azure_asn: int
:param peer_asn: The peer ASN.
:type peer_asn: long
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:ivar primary_azure_port: The primary port.
:vartype primary_azure_port: str
:ivar secondary_azure_port: The secondary port.
:vartype secondary_azure_port: str
:param shared_key: The shared key.
:type shared_key: str
:param vlan_id: The VLAN ID.
:type vlan_id: int
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringConfig
:ivar provisioning_state: The provisioning state of the express route cross connection peering
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:ivar last_modified_by: Who was the last to modify the peering.
:vartype last_modified_by: str
:param ipv6_peering_config: The IPv6 peering configuration.
:type ipv6_peering_config:
~azure.mgmt.network.v2020_04_01.models.Ipv6ExpressRouteCircuitPeeringConfig
"""
_validation = {
'etag': {'readonly': True},
'azure_asn': {'readonly': True},
'peer_asn': {'maximum': 4294967295, 'minimum': 1},
'primary_azure_port': {'readonly': True},
'secondary_azure_port': {'readonly': True},
'provisioning_state': {'readonly': True},
'last_modified_by': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'peering_type': {'key': 'properties.peeringType', 'type': 'str'},
'state': {'key': 'properties.state', 'type': 'str'},
'azure_asn': {'key': 'properties.azureASN', 'type': 'int'},
'peer_asn': {'key': 'properties.peerASN', 'type': 'long'},
'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'vlan_id': {'key': 'properties.vlanId', 'type': 'int'},
'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'},
'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.peering_type = kwargs.get('peering_type', None)
self.state = kwargs.get('state', None)
self.azure_asn = None
self.peer_asn = kwargs.get('peer_asn', None)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.primary_azure_port = None
self.secondary_azure_port = None
self.shared_key = kwargs.get('shared_key', None)
self.vlan_id = kwargs.get('vlan_id', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.provisioning_state = None
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.last_modified_by = None
self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None)
class ExpressRouteCrossConnectionPeeringList(msrest.serialization.Model):
"""Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCrossConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The peerings in an express route cross connection.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionPeering]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnectionPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionPeeringList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteCrossConnectionRoutesTableSummary(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param neighbor: IP address of Neighbor router.
:type neighbor: str
:param asn: Autonomous system number.
:type asn: int
:param up_down: The length of time that the BGP session has been in the Established state, or
the current status if not in the Established state.
:type up_down: str
:param state_or_prefixes_received: Current state of the BGP session, and the number of prefixes
that have been received from a neighbor or peer group.
:type state_or_prefixes_received: str
"""
_attribute_map = {
'neighbor': {'key': 'neighbor', 'type': 'str'},
'asn': {'key': 'asn', 'type': 'int'},
'up_down': {'key': 'upDown', 'type': 'str'},
'state_or_prefixes_received': {'key': 'stateOrPrefixesReceived', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionRoutesTableSummary, self).__init__(**kwargs)
self.neighbor = kwargs.get('neighbor', None)
self.asn = kwargs.get('asn', None)
self.up_down = kwargs.get('up_down', None)
self.state_or_prefixes_received = kwargs.get('state_or_prefixes_received', None)
class ExpressRouteCrossConnectionsRoutesTableSummaryListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Cross Connections.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of the routes table.
:type value:
list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionRoutesTableSummary]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnectionRoutesTableSummary]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionsRoutesTableSummaryListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteGateway(Resource):
"""ExpressRoute gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param auto_scale_configuration: Configuration for auto scaling.
:type auto_scale_configuration:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteGatewayPropertiesAutoScaleConfiguration
:ivar express_route_connections: List of ExpressRoute connections to the ExpressRoute gateway.
:vartype express_route_connections:
list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteConnection]
:ivar provisioning_state: The provisioning state of the express route gateway resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param virtual_hub: The Virtual Hub where the ExpressRoute gateway is or will be deployed.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.VirtualHubId
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'express_route_connections': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'auto_scale_configuration': {'key': 'properties.autoScaleConfiguration', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfiguration'},
'express_route_connections': {'key': 'properties.expressRouteConnections', 'type': '[ExpressRouteConnection]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'VirtualHubId'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGateway, self).__init__(**kwargs)
self.etag = None
self.auto_scale_configuration = kwargs.get('auto_scale_configuration', None)
self.express_route_connections = None
self.provisioning_state = None
self.virtual_hub = kwargs.get('virtual_hub', None)
class ExpressRouteGatewayList(msrest.serialization.Model):
"""List of ExpressRoute gateways.
:param value: List of ExpressRoute gateways.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteGateway]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteGateway]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ExpressRouteGatewayPropertiesAutoScaleConfiguration(msrest.serialization.Model):
"""Configuration for auto scaling.
:param bounds: Minimum and maximum number of scale units to deploy.
:type bounds:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds
"""
_attribute_map = {
'bounds': {'key': 'bounds', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayPropertiesAutoScaleConfiguration, self).__init__(**kwargs)
self.bounds = kwargs.get('bounds', None)
class ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds(msrest.serialization.Model):
"""Minimum and maximum number of scale units to deploy.
:param min: Minimum number of scale units deployed for ExpressRoute gateway.
:type min: int
:param max: Maximum number of scale units deployed for ExpressRoute gateway.
:type max: int
"""
_attribute_map = {
'min': {'key': 'min', 'type': 'int'},
'max': {'key': 'max', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds, self).__init__(**kwargs)
self.min = kwargs.get('min', None)
self.max = kwargs.get('max', None)
class ExpressRouteLink(SubResource):
"""ExpressRouteLink child resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of child port resource that is unique among child port resources of the
parent.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar router_name: Name of Azure router associated with physical port.
:vartype router_name: str
:ivar interface_name: Name of Azure router interface.
:vartype interface_name: str
:ivar patch_panel_id: Mapping between physical port to patch panel port.
:vartype patch_panel_id: str
:ivar rack_id: Mapping of physical patch panel to rack.
:vartype rack_id: str
:ivar connector_type: Physical fiber port type. Possible values include: "LC", "SC".
:vartype connector_type: str or
~azure.mgmt.network.v2020_04_01.models.ExpressRouteLinkConnectorType
:param admin_state: Administrative state of the physical port. Possible values include:
"Enabled", "Disabled".
:type admin_state: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRouteLinkAdminState
:ivar provisioning_state: The provisioning state of the express route link resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param mac_sec_config: MacSec configuration.
:type mac_sec_config: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteLinkMacSecConfig
"""
_validation = {
'etag': {'readonly': True},
'router_name': {'readonly': True},
'interface_name': {'readonly': True},
'patch_panel_id': {'readonly': True},
'rack_id': {'readonly': True},
'connector_type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'router_name': {'key': 'properties.routerName', 'type': 'str'},
'interface_name': {'key': 'properties.interfaceName', 'type': 'str'},
'patch_panel_id': {'key': 'properties.patchPanelId', 'type': 'str'},
'rack_id': {'key': 'properties.rackId', 'type': 'str'},
'connector_type': {'key': 'properties.connectorType', 'type': 'str'},
'admin_state': {'key': 'properties.adminState', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'mac_sec_config': {'key': 'properties.macSecConfig', 'type': 'ExpressRouteLinkMacSecConfig'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.router_name = None
self.interface_name = None
self.patch_panel_id = None
self.rack_id = None
self.connector_type = None
self.admin_state = kwargs.get('admin_state', None)
self.provisioning_state = None
self.mac_sec_config = kwargs.get('mac_sec_config', None)
class ExpressRouteLinkListResult(msrest.serialization.Model):
"""Response for ListExpressRouteLinks API service call.
:param value: The list of ExpressRouteLink sub-resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteLink]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteLinkListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteLinkMacSecConfig(msrest.serialization.Model):
"""ExpressRouteLink Mac Security Configuration.
:param ckn_secret_identifier: Keyvault Secret Identifier URL containing Mac security CKN key.
:type ckn_secret_identifier: str
:param cak_secret_identifier: Keyvault Secret Identifier URL containing Mac security CAK key.
:type cak_secret_identifier: str
:param cipher: Mac security cipher. Possible values include: "gcm-aes-128", "gcm-aes-256".
:type cipher: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRouteLinkMacSecCipher
"""
_attribute_map = {
'ckn_secret_identifier': {'key': 'cknSecretIdentifier', 'type': 'str'},
'cak_secret_identifier': {'key': 'cakSecretIdentifier', 'type': 'str'},
'cipher': {'key': 'cipher', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteLinkMacSecConfig, self).__init__(**kwargs)
self.ckn_secret_identifier = kwargs.get('ckn_secret_identifier', None)
self.cak_secret_identifier = kwargs.get('cak_secret_identifier', None)
self.cipher = kwargs.get('cipher', None)
class ExpressRoutePort(Resource):
"""ExpressRoutePort resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param identity: The identity of ExpressRoutePort, if configured.
:type identity: ~azure.mgmt.network.v2020_04_01.models.ManagedServiceIdentity
:param peering_location: The name of the peering location that the ExpressRoutePort is mapped
to physically.
:type peering_location: str
:param bandwidth_in_gbps: Bandwidth of procured ports in Gbps.
:type bandwidth_in_gbps: int
:ivar provisioned_bandwidth_in_gbps: Aggregate Gbps of associated circuit bandwidths.
:vartype provisioned_bandwidth_in_gbps: float
:ivar mtu: Maximum transmission unit of the physical port pair(s).
:vartype mtu: str
:param encapsulation: Encapsulation method on physical ports. Possible values include: "Dot1Q",
"QinQ".
:type encapsulation: str or
~azure.mgmt.network.v2020_04_01.models.ExpressRoutePortsEncapsulation
:ivar ether_type: Ether type of the physical port.
:vartype ether_type: str
:ivar allocation_date: Date of the physical port allocation to be used in Letter of
Authorization.
:vartype allocation_date: str
:param links: The set of physical links of the ExpressRoutePort resource.
:type links: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteLink]
:ivar circuits: Reference the ExpressRoute circuit(s) that are provisioned on this
ExpressRoutePort resource.
:vartype circuits: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the express route port resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar resource_guid: The resource GUID property of the express route port resource.
:vartype resource_guid: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioned_bandwidth_in_gbps': {'readonly': True},
'mtu': {'readonly': True},
'ether_type': {'readonly': True},
'allocation_date': {'readonly': True},
'circuits': {'readonly': True},
'provisioning_state': {'readonly': True},
'resource_guid': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'ManagedServiceIdentity'},
'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'},
'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'int'},
'provisioned_bandwidth_in_gbps': {'key': 'properties.provisionedBandwidthInGbps', 'type': 'float'},
'mtu': {'key': 'properties.mtu', 'type': 'str'},
'encapsulation': {'key': 'properties.encapsulation', 'type': 'str'},
'ether_type': {'key': 'properties.etherType', 'type': 'str'},
'allocation_date': {'key': 'properties.allocationDate', 'type': 'str'},
'links': {'key': 'properties.links', 'type': '[ExpressRouteLink]'},
'circuits': {'key': 'properties.circuits', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePort, self).__init__(**kwargs)
self.etag = None
self.identity = kwargs.get('identity', None)
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None)
self.provisioned_bandwidth_in_gbps = None
self.mtu = None
self.encapsulation = kwargs.get('encapsulation', None)
self.ether_type = None
self.allocation_date = None
self.links = kwargs.get('links', None)
self.circuits = None
self.provisioning_state = None
self.resource_guid = None
class ExpressRoutePortListResult(msrest.serialization.Model):
"""Response for ListExpressRoutePorts API service call.
:param value: A list of ExpressRoutePort resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRoutePort]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRoutePort]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRoutePortsLocation(Resource):
"""Definition of the ExpressRoutePorts peering location resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar address: Address of peering location.
:vartype address: str
:ivar contact: Contact details of peering locations.
:vartype contact: str
:param available_bandwidths: The inventory of available ExpressRoutePort bandwidths.
:type available_bandwidths:
list[~azure.mgmt.network.v2020_04_01.models.ExpressRoutePortsLocationBandwidths]
:ivar provisioning_state: The provisioning state of the express route port location resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'address': {'readonly': True},
'contact': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'address': {'key': 'properties.address', 'type': 'str'},
'contact': {'key': 'properties.contact', 'type': 'str'},
'available_bandwidths': {'key': 'properties.availableBandwidths', 'type': '[ExpressRoutePortsLocationBandwidths]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocation, self).__init__(**kwargs)
self.address = None
self.contact = None
self.available_bandwidths = kwargs.get('available_bandwidths', None)
self.provisioning_state = None
class ExpressRoutePortsLocationBandwidths(msrest.serialization.Model):
"""Real-time inventory of available ExpressRoute port bandwidths.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar offer_name: Bandwidth descriptive name.
:vartype offer_name: str
:ivar value_in_gbps: Bandwidth value in Gbps.
:vartype value_in_gbps: int
"""
_validation = {
'offer_name': {'readonly': True},
'value_in_gbps': {'readonly': True},
}
_attribute_map = {
'offer_name': {'key': 'offerName', 'type': 'str'},
'value_in_gbps': {'key': 'valueInGbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocationBandwidths, self).__init__(**kwargs)
self.offer_name = None
self.value_in_gbps = None
class ExpressRoutePortsLocationListResult(msrest.serialization.Model):
"""Response for ListExpressRoutePortsLocations API service call.
:param value: The list of all ExpressRoutePort peering locations.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRoutePortsLocation]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRoutePortsLocation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteServiceProvider(Resource):
"""A ExpressRouteResourceProvider object.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param peering_locations: A list of peering locations.
:type peering_locations: list[str]
:param bandwidths_offered: A list of bandwidths offered.
:type bandwidths_offered:
list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteServiceProviderBandwidthsOffered]
:ivar provisioning_state: The provisioning state of the express route service provider
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'peering_locations': {'key': 'properties.peeringLocations', 'type': '[str]'},
'bandwidths_offered': {'key': 'properties.bandwidthsOffered', 'type': '[ExpressRouteServiceProviderBandwidthsOffered]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProvider, self).__init__(**kwargs)
self.peering_locations = kwargs.get('peering_locations', None)
self.bandwidths_offered = kwargs.get('bandwidths_offered', None)
self.provisioning_state = None
class ExpressRouteServiceProviderBandwidthsOffered(msrest.serialization.Model):
"""Contains bandwidths offered in ExpressRouteServiceProvider resources.
:param offer_name: The OfferName.
:type offer_name: str
:param value_in_mbps: The ValueInMbps.
:type value_in_mbps: int
"""
_attribute_map = {
'offer_name': {'key': 'offerName', 'type': 'str'},
'value_in_mbps': {'key': 'valueInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProviderBandwidthsOffered, self).__init__(**kwargs)
self.offer_name = kwargs.get('offer_name', None)
self.value_in_mbps = kwargs.get('value_in_mbps', None)
class ExpressRouteServiceProviderListResult(msrest.serialization.Model):
"""Response for the ListExpressRouteServiceProvider API service call.
:param value: A list of ExpressRouteResourceProvider resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteServiceProvider]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteServiceProvider]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProviderListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class FirewallPolicy(Resource):
"""FirewallPolicy Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar rule_groups: List of references to FirewallPolicyRuleGroups.
:vartype rule_groups: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the firewall policy resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param base_policy: The parent firewall policy from which rules are inherited.
:type base_policy: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar firewalls: List of references to Azure Firewalls that this Firewall Policy is associated
with.
:vartype firewalls: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar child_policies: List of references to Child Firewall Policies.
:vartype child_policies: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param threat_intel_mode: The operation mode for Threat Intelligence. Possible values include:
"Alert", "Deny", "Off".
:type threat_intel_mode: str or
~azure.mgmt.network.v2020_04_01.models.AzureFirewallThreatIntelMode
:param threat_intel_whitelist: ThreatIntel Whitelist for Firewall Policy.
:type threat_intel_whitelist:
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyThreatIntelWhitelist
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'rule_groups': {'readonly': True},
'provisioning_state': {'readonly': True},
'firewalls': {'readonly': True},
'child_policies': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'rule_groups': {'key': 'properties.ruleGroups', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'base_policy': {'key': 'properties.basePolicy', 'type': 'SubResource'},
'firewalls': {'key': 'properties.firewalls', 'type': '[SubResource]'},
'child_policies': {'key': 'properties.childPolicies', 'type': '[SubResource]'},
'threat_intel_mode': {'key': 'properties.threatIntelMode', 'type': 'str'},
'threat_intel_whitelist': {'key': 'properties.threatIntelWhitelist', 'type': 'FirewallPolicyThreatIntelWhitelist'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicy, self).__init__(**kwargs)
self.etag = None
self.rule_groups = None
self.provisioning_state = None
self.base_policy = kwargs.get('base_policy', None)
self.firewalls = None
self.child_policies = None
self.threat_intel_mode = kwargs.get('threat_intel_mode', None)
self.threat_intel_whitelist = kwargs.get('threat_intel_whitelist', None)
class FirewallPolicyRule(msrest.serialization.Model):
"""Properties of the rule.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: FirewallPolicyFilterRule, FirewallPolicyNatRule.
All required parameters must be populated in order to send to Azure.
:param rule_type: Required. The type of the rule.Constant filled by server. Possible values
include: "FirewallPolicyNatRule", "FirewallPolicyFilterRule".
:type rule_type: str or ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleType
:param name: The name of the rule.
:type name: str
:param priority: Priority of the Firewall Policy Rule resource.
:type priority: int
"""
_validation = {
'rule_type': {'required': True},
'priority': {'maximum': 65000, 'minimum': 100},
}
_attribute_map = {
'rule_type': {'key': 'ruleType', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
}
_subtype_map = {
'rule_type': {'FirewallPolicyFilterRule': 'FirewallPolicyFilterRule', 'FirewallPolicyNatRule': 'FirewallPolicyNatRule'}
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyRule, self).__init__(**kwargs)
self.rule_type = None # type: Optional[str]
self.name = kwargs.get('name', None)
self.priority = kwargs.get('priority', None)
class FirewallPolicyFilterRule(FirewallPolicyRule):
"""Firewall Policy Filter Rule.
All required parameters must be populated in order to send to Azure.
:param rule_type: Required. The type of the rule.Constant filled by server. Possible values
include: "FirewallPolicyNatRule", "FirewallPolicyFilterRule".
:type rule_type: str or ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleType
:param name: The name of the rule.
:type name: str
:param priority: Priority of the Firewall Policy Rule resource.
:type priority: int
:param action: The action type of a Filter rule.
:type action: ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyFilterRuleAction
:param rule_conditions: Collection of rule conditions used by a rule.
:type rule_conditions: list[~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleCondition]
"""
_validation = {
'rule_type': {'required': True},
'priority': {'maximum': 65000, 'minimum': 100},
}
_attribute_map = {
'rule_type': {'key': 'ruleType', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'action': {'key': 'action', 'type': 'FirewallPolicyFilterRuleAction'},
'rule_conditions': {'key': 'ruleConditions', 'type': '[FirewallPolicyRuleCondition]'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyFilterRule, self).__init__(**kwargs)
self.rule_type = 'FirewallPolicyFilterRule' # type: str
self.action = kwargs.get('action', None)
self.rule_conditions = kwargs.get('rule_conditions', None)
class FirewallPolicyFilterRuleAction(msrest.serialization.Model):
"""Properties of the FirewallPolicyFilterRuleAction.
:param type: The type of action. Possible values include: "Allow", "Deny".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyFilterRuleActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyFilterRuleAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class FirewallPolicyListResult(msrest.serialization.Model):
"""Response for ListFirewallPolicies API service call.
:param value: List of Firewall Policies in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.FirewallPolicy]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[FirewallPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class FirewallPolicyNatRule(FirewallPolicyRule):
"""Firewall Policy NAT Rule.
All required parameters must be populated in order to send to Azure.
:param rule_type: Required. The type of the rule.Constant filled by server. Possible values
include: "FirewallPolicyNatRule", "FirewallPolicyFilterRule".
:type rule_type: str or ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleType
:param name: The name of the rule.
:type name: str
:param priority: Priority of the Firewall Policy Rule resource.
:type priority: int
:param action: The action type of a Nat rule.
:type action: ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyNatRuleAction
:param translated_address: The translated address for this NAT rule.
:type translated_address: str
:param translated_port: The translated port for this NAT rule.
:type translated_port: str
:param rule_condition: The match conditions for incoming traffic.
:type rule_condition: ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleCondition
"""
_validation = {
'rule_type': {'required': True},
'priority': {'maximum': 65000, 'minimum': 100},
}
_attribute_map = {
'rule_type': {'key': 'ruleType', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'action': {'key': 'action', 'type': 'FirewallPolicyNatRuleAction'},
'translated_address': {'key': 'translatedAddress', 'type': 'str'},
'translated_port': {'key': 'translatedPort', 'type': 'str'},
'rule_condition': {'key': 'ruleCondition', 'type': 'FirewallPolicyRuleCondition'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyNatRule, self).__init__(**kwargs)
self.rule_type = 'FirewallPolicyNatRule' # type: str
self.action = kwargs.get('action', None)
self.translated_address = kwargs.get('translated_address', None)
self.translated_port = kwargs.get('translated_port', None)
self.rule_condition = kwargs.get('rule_condition', None)
class FirewallPolicyNatRuleAction(msrest.serialization.Model):
"""Properties of the FirewallPolicyNatRuleAction.
:param type: The type of action. Possible values include: "DNAT".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.FirewallPolicyNatRuleActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyNatRuleAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class FirewallPolicyRuleConditionApplicationProtocol(msrest.serialization.Model):
"""Properties of the application rule protocol.
:param protocol_type: Protocol type. Possible values include: "Http", "Https".
:type protocol_type: str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionApplicationProtocolType
:param port: Port number for the protocol, cannot be greater than 64000.
:type port: int
"""
_validation = {
'port': {'maximum': 64000, 'minimum': 0},
}
_attribute_map = {
'protocol_type': {'key': 'protocolType', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyRuleConditionApplicationProtocol, self).__init__(**kwargs)
self.protocol_type = kwargs.get('protocol_type', None)
self.port = kwargs.get('port', None)
class FirewallPolicyRuleGroup(SubResource):
"""Rule Group resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Rule Group type.
:vartype type: str
:param priority: Priority of the Firewall Policy Rule Group resource.
:type priority: int
:param rules: Group of Firewall Policy rules.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRule]
:ivar provisioning_state: The provisioning state of the firewall policy rule group resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'rules': {'key': 'properties.rules', 'type': '[FirewallPolicyRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyRuleGroup, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.priority = kwargs.get('priority', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class FirewallPolicyRuleGroupListResult(msrest.serialization.Model):
"""Response for ListFirewallPolicyRuleGroups API service call.
:param value: List of FirewallPolicyRuleGroups in a FirewallPolicy.
:type value: list[~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleGroup]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[FirewallPolicyRuleGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyRuleGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class FirewallPolicyThreatIntelWhitelist(msrest.serialization.Model):
"""ThreatIntel Whitelist for Firewall Policy.
:param ip_addresses: List of IP addresses for the ThreatIntel Whitelist.
:type ip_addresses: list[str]
:param fqdns: List of FQDNs for the ThreatIntel Whitelist.
:type fqdns: list[str]
"""
_attribute_map = {
'ip_addresses': {'key': 'ipAddresses', 'type': '[str]'},
'fqdns': {'key': 'fqdns', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(FirewallPolicyThreatIntelWhitelist, self).__init__(**kwargs)
self.ip_addresses = kwargs.get('ip_addresses', None)
self.fqdns = kwargs.get('fqdns', None)
class FlowLog(Resource):
"""A flow log resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param target_resource_id: ID of network security group to which flow log will be applied.
:type target_resource_id: str
:ivar target_resource_guid: Guid of network security group to which flow log will be applied.
:vartype target_resource_guid: str
:param storage_id: ID of the storage account which is used to store the flow log.
:type storage_id: str
:param enabled: Flag to enable/disable flow logging.
:type enabled: bool
:param retention_policy: Parameters that define the retention policy for flow log.
:type retention_policy: ~azure.mgmt.network.v2020_04_01.models.RetentionPolicyParameters
:param format: Parameters that define the flow log format.
:type format: ~azure.mgmt.network.v2020_04_01.models.FlowLogFormatParameters
:param flow_analytics_configuration: Parameters that define the configuration of traffic
analytics.
:type flow_analytics_configuration:
~azure.mgmt.network.v2020_04_01.models.TrafficAnalyticsProperties
:ivar provisioning_state: The provisioning state of the flow log. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'target_resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'target_resource_id': {'key': 'properties.targetResourceId', 'type': 'str'},
'target_resource_guid': {'key': 'properties.targetResourceGuid', 'type': 'str'},
'storage_id': {'key': 'properties.storageId', 'type': 'str'},
'enabled': {'key': 'properties.enabled', 'type': 'bool'},
'retention_policy': {'key': 'properties.retentionPolicy', 'type': 'RetentionPolicyParameters'},
'format': {'key': 'properties.format', 'type': 'FlowLogFormatParameters'},
'flow_analytics_configuration': {'key': 'properties.flowAnalyticsConfiguration', 'type': 'TrafficAnalyticsProperties'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FlowLog, self).__init__(**kwargs)
self.etag = None
self.target_resource_id = kwargs.get('target_resource_id', None)
self.target_resource_guid = None
self.storage_id = kwargs.get('storage_id', None)
self.enabled = kwargs.get('enabled', None)
self.retention_policy = kwargs.get('retention_policy', None)
self.format = kwargs.get('format', None)
self.flow_analytics_configuration = kwargs.get('flow_analytics_configuration', None)
self.provisioning_state = None
class FlowLogFormatParameters(msrest.serialization.Model):
"""Parameters that define the flow log format.
:param type: The file type of flow log. Possible values include: "JSON".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.FlowLogFormatType
:param version: The version (revision) of the flow log.
:type version: int
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(FlowLogFormatParameters, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', 0)
class FlowLogInformation(msrest.serialization.Model):
"""Information on the configuration of flow log and traffic analytics (optional) .
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the resource to configure for flow log and
traffic analytics (optional) .
:type target_resource_id: str
:param flow_analytics_configuration: Parameters that define the configuration of traffic
analytics.
:type flow_analytics_configuration:
~azure.mgmt.network.v2020_04_01.models.TrafficAnalyticsProperties
:param storage_id: Required. ID of the storage account which is used to store the flow log.
:type storage_id: str
:param enabled: Required. Flag to enable/disable flow logging.
:type enabled: bool
:param retention_policy: Parameters that define the retention policy for flow log.
:type retention_policy: ~azure.mgmt.network.v2020_04_01.models.RetentionPolicyParameters
:param format: Parameters that define the flow log format.
:type format: ~azure.mgmt.network.v2020_04_01.models.FlowLogFormatParameters
"""
_validation = {
'target_resource_id': {'required': True},
'storage_id': {'required': True},
'enabled': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'flow_analytics_configuration': {'key': 'flowAnalyticsConfiguration', 'type': 'TrafficAnalyticsProperties'},
'storage_id': {'key': 'properties.storageId', 'type': 'str'},
'enabled': {'key': 'properties.enabled', 'type': 'bool'},
'retention_policy': {'key': 'properties.retentionPolicy', 'type': 'RetentionPolicyParameters'},
'format': {'key': 'properties.format', 'type': 'FlowLogFormatParameters'},
}
def __init__(
self,
**kwargs
):
super(FlowLogInformation, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.flow_analytics_configuration = kwargs.get('flow_analytics_configuration', None)
self.storage_id = kwargs['storage_id']
self.enabled = kwargs['enabled']
self.retention_policy = kwargs.get('retention_policy', None)
self.format = kwargs.get('format', None)
class FlowLogListResult(msrest.serialization.Model):
"""List of flow logs.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Information about flow log resource.
:type value: list[~azure.mgmt.network.v2020_04_01.models.FlowLog]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[FlowLog]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FlowLogListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class FlowLogStatusParameters(msrest.serialization.Model):
"""Parameters that define a resource to query flow log and traffic analytics (optional) status.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource where getting the flow log and traffic
analytics (optional) status.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FlowLogStatusParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class FrontendIPConfiguration(SubResource):
"""Frontend IP address of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of frontend IP
configurations used by the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:ivar inbound_nat_rules: An array of references to inbound rules that use this frontend IP.
:vartype inbound_nat_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar inbound_nat_pools: An array of references to inbound pools that use this frontend IP.
:vartype inbound_nat_pools: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar outbound_rules: An array of references to outbound rules that use this frontend IP.
:vartype outbound_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar load_balancing_rules: An array of references to load balancing rules that use this
frontend IP.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The Private IP allocation method. Possible values include:
"Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param private_ip_address_version: Whether the specific ipconfiguration is IPv4 or IPv6.
Default is taken as IPv4. Possible values include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
:param subnet: The reference to the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:param public_ip_address: The reference to the Public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.PublicIPAddress
:param public_ip_prefix: The reference to the Public IP Prefix resource.
:type public_ip_prefix: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the frontend IP configuration resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'inbound_nat_rules': {'readonly': True},
'inbound_nat_pools': {'readonly': True},
'outbound_rules': {'readonly': True},
'load_balancing_rules': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[SubResource]'},
'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[SubResource]'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FrontendIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.zones = kwargs.get('zones', None)
self.inbound_nat_rules = None
self.inbound_nat_pools = None
self.outbound_rules = None
self.load_balancing_rules = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.public_ip_prefix = kwargs.get('public_ip_prefix', None)
self.provisioning_state = None
class GatewayRoute(msrest.serialization.Model):
"""Gateway routing details.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar local_address: The gateway's local address.
:vartype local_address: str
:ivar network: The route's network prefix.
:vartype network: str
:ivar next_hop: The route's next hop.
:vartype next_hop: str
:ivar source_peer: The peer this route was learned from.
:vartype source_peer: str
:ivar origin: The source this route was learned from.
:vartype origin: str
:ivar as_path: The route's AS path sequence.
:vartype as_path: str
:ivar weight: The route's weight.
:vartype weight: int
"""
_validation = {
'local_address': {'readonly': True},
'network': {'readonly': True},
'next_hop': {'readonly': True},
'source_peer': {'readonly': True},
'origin': {'readonly': True},
'as_path': {'readonly': True},
'weight': {'readonly': True},
}
_attribute_map = {
'local_address': {'key': 'localAddress', 'type': 'str'},
'network': {'key': 'network', 'type': 'str'},
'next_hop': {'key': 'nextHop', 'type': 'str'},
'source_peer': {'key': 'sourcePeer', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'as_path': {'key': 'asPath', 'type': 'str'},
'weight': {'key': 'weight', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(GatewayRoute, self).__init__(**kwargs)
self.local_address = None
self.network = None
self.next_hop = None
self.source_peer = None
self.origin = None
self.as_path = None
self.weight = None
class GatewayRouteListResult(msrest.serialization.Model):
"""List of virtual network gateway routes.
:param value: List of gateway routes.
:type value: list[~azure.mgmt.network.v2020_04_01.models.GatewayRoute]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[GatewayRoute]'},
}
def __init__(
self,
**kwargs
):
super(GatewayRouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class GetVpnSitesConfigurationRequest(msrest.serialization.Model):
"""List of Vpn-Sites.
All required parameters must be populated in order to send to Azure.
:param vpn_sites: List of resource-ids of the vpn-sites for which config is to be downloaded.
:type vpn_sites: list[str]
:param output_blob_sas_url: Required. The sas-url to download the configurations for vpn-sites.
:type output_blob_sas_url: str
"""
_validation = {
'output_blob_sas_url': {'required': True},
}
_attribute_map = {
'vpn_sites': {'key': 'vpnSites', 'type': '[str]'},
'output_blob_sas_url': {'key': 'outputBlobSasUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(GetVpnSitesConfigurationRequest, self).__init__(**kwargs)
self.vpn_sites = kwargs.get('vpn_sites', None)
self.output_blob_sas_url = kwargs['output_blob_sas_url']
class HTTPConfiguration(msrest.serialization.Model):
"""HTTP configuration of the connectivity check.
:param method: HTTP method. Possible values include: "Get".
:type method: str or ~azure.mgmt.network.v2020_04_01.models.HTTPMethod
:param headers: List of HTTP headers.
:type headers: list[~azure.mgmt.network.v2020_04_01.models.HTTPHeader]
:param valid_status_codes: Valid status codes.
:type valid_status_codes: list[int]
"""
_attribute_map = {
'method': {'key': 'method', 'type': 'str'},
'headers': {'key': 'headers', 'type': '[HTTPHeader]'},
'valid_status_codes': {'key': 'validStatusCodes', 'type': '[int]'},
}
def __init__(
self,
**kwargs
):
super(HTTPConfiguration, self).__init__(**kwargs)
self.method = kwargs.get('method', None)
self.headers = kwargs.get('headers', None)
self.valid_status_codes = kwargs.get('valid_status_codes', None)
class HTTPHeader(msrest.serialization.Model):
"""The HTTP header.
:param name: The name in HTTP header.
:type name: str
:param value: The value in HTTP header.
:type value: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HTTPHeader, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.value = kwargs.get('value', None)
class HubIPAddresses(msrest.serialization.Model):
"""IP addresses associated with azure firewall.
:param public_ip_addresses: List of Public IP addresses associated with azure firewall.
:type public_ip_addresses:
list[~azure.mgmt.network.v2020_04_01.models.AzureFirewallPublicIPAddress]
:param private_ip_address: Private IP Address associated with azure firewall.
:type private_ip_address: str
"""
_attribute_map = {
'public_ip_addresses': {'key': 'publicIPAddresses', 'type': '[AzureFirewallPublicIPAddress]'},
'private_ip_address': {'key': 'privateIPAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HubIPAddresses, self).__init__(**kwargs)
self.public_ip_addresses = kwargs.get('public_ip_addresses', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
class HubRoute(msrest.serialization.Model):
"""RouteTable route.
All required parameters must be populated in order to send to Azure.
:param name: Required. The name of the Route that is unique within a RouteTable. This name can
be used to access this route.
:type name: str
:param destination_type: Required. The type of destinations (eg: CIDR, ResourceId, Service).
:type destination_type: str
:param destinations: Required. List of all destinations.
:type destinations: list[str]
:param next_hop_type: Required. The type of next hop (eg: ResourceId).
:type next_hop_type: str
:param next_hop: Required. NextHop resource ID.
:type next_hop: str
"""
_validation = {
'name': {'required': True},
'destination_type': {'required': True},
'destinations': {'required': True},
'next_hop_type': {'required': True},
'next_hop': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'destination_type': {'key': 'destinationType', 'type': 'str'},
'destinations': {'key': 'destinations', 'type': '[str]'},
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
'next_hop': {'key': 'nextHop', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HubRoute, self).__init__(**kwargs)
self.name = kwargs['name']
self.destination_type = kwargs['destination_type']
self.destinations = kwargs['destinations']
self.next_hop_type = kwargs['next_hop_type']
self.next_hop = kwargs['next_hop']
class HubRouteTable(SubResource):
"""RouteTable resource in a virtual hub.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param routes: List of all routes.
:type routes: list[~azure.mgmt.network.v2020_04_01.models.HubRoute]
:param labels: List of labels associated with this route table.
:type labels: list[str]
:ivar associated_connections: List of all connections associated with this route table.
:vartype associated_connections: list[str]
:ivar propagating_connections: List of all connections that advertise to this route table.
:vartype propagating_connections: list[str]
:ivar provisioning_state: The provisioning state of the RouteTable resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'associated_connections': {'readonly': True},
'propagating_connections': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'routes': {'key': 'properties.routes', 'type': '[HubRoute]'},
'labels': {'key': 'properties.labels', 'type': '[str]'},
'associated_connections': {'key': 'properties.associatedConnections', 'type': '[str]'},
'propagating_connections': {'key': 'properties.propagatingConnections', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HubRouteTable, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.routes = kwargs.get('routes', None)
self.labels = kwargs.get('labels', None)
self.associated_connections = None
self.propagating_connections = None
self.provisioning_state = None
class HubVirtualNetworkConnection(SubResource):
"""HubVirtualNetworkConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param remote_virtual_network: Reference to the remote virtual network.
:type remote_virtual_network: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param allow_hub_to_remote_vnet_transit: VirtualHub to RemoteVnet transit to enabled or not.
:type allow_hub_to_remote_vnet_transit: bool
:param allow_remote_vnet_to_use_hub_vnet_gateways: Allow RemoteVnet to use Virtual Hub's
gateways.
:type allow_remote_vnet_to_use_hub_vnet_gateways: bool
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:param routing_configuration: The Routing Configuration indicating the associated and
propagated route tables on this connection.
:type routing_configuration: ~azure.mgmt.network.v2020_04_01.models.RoutingConfiguration
:ivar provisioning_state: The provisioning state of the hub virtual network connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'},
'allow_hub_to_remote_vnet_transit': {'key': 'properties.allowHubToRemoteVnetTransit', 'type': 'bool'},
'allow_remote_vnet_to_use_hub_vnet_gateways': {'key': 'properties.allowRemoteVnetToUseHubVnetGateways', 'type': 'bool'},
'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'},
'routing_configuration': {'key': 'properties.routingConfiguration', 'type': 'RoutingConfiguration'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HubVirtualNetworkConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.remote_virtual_network = kwargs.get('remote_virtual_network', None)
self.allow_hub_to_remote_vnet_transit = kwargs.get('allow_hub_to_remote_vnet_transit', None)
self.allow_remote_vnet_to_use_hub_vnet_gateways = kwargs.get('allow_remote_vnet_to_use_hub_vnet_gateways', None)
self.enable_internet_security = kwargs.get('enable_internet_security', None)
self.routing_configuration = kwargs.get('routing_configuration', None)
self.provisioning_state = None
class InboundNatPool(SubResource):
"""Inbound NAT pool of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of inbound NAT pools used
by the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param protocol: The reference to the transport protocol used by the inbound NAT pool. Possible
values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.TransportProtocol
:param frontend_port_range_start: The first port number in the range of external ports that
will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values
range between 1 and 65534.
:type frontend_port_range_start: int
:param frontend_port_range_end: The last port number in the range of external ports that will
be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range
between 1 and 65535.
:type frontend_port_range_end: int
:param backend_port: The port used for internal connections on the endpoint. Acceptable values
are between 1 and 65535.
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:ivar provisioning_state: The provisioning state of the inbound NAT pool resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'frontend_port_range_start': {'key': 'properties.frontendPortRangeStart', 'type': 'int'},
'frontend_port_range_end': {'key': 'properties.frontendPortRangeEnd', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.protocol = kwargs.get('protocol', None)
self.frontend_port_range_start = kwargs.get('frontend_port_range_start', None)
self.frontend_port_range_end = kwargs.get('frontend_port_range_end', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.provisioning_state = None
class InboundNatRule(SubResource):
"""Inbound NAT rule of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of inbound NAT rules used
by the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar backend_ip_configuration: A reference to a private IP address defined on a network
interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations
is forwarded to the backend IP.
:vartype backend_ip_configuration:
~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration
:param protocol: The reference to the transport protocol used by the load balancing rule.
Possible values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.TransportProtocol
:param frontend_port: The port for the external endpoint. Port numbers for each rule must be
unique within the Load Balancer. Acceptable values range from 1 to 65534.
:type frontend_port: int
:param backend_port: The port used for the internal endpoint. Acceptable values range from 1 to
65535.
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:ivar provisioning_state: The provisioning state of the inbound NAT rule resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'backend_ip_configuration': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'backend_ip_configuration': {'key': 'properties.backendIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.backend_ip_configuration = None
self.protocol = kwargs.get('protocol', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.provisioning_state = None
class InboundNatRuleListResult(msrest.serialization.Model):
"""Response for ListInboundNatRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of inbound nat rules in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.InboundNatRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[InboundNatRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class IPAddressAvailabilityResult(msrest.serialization.Model):
"""Response for CheckIPAddressAvailability API service call.
:param available: Private IP address availability.
:type available: bool
:param available_ip_addresses: Contains other available private IP addresses if the asked for
address is taken.
:type available_ip_addresses: list[str]
"""
_attribute_map = {
'available': {'key': 'available', 'type': 'bool'},
'available_ip_addresses': {'key': 'availableIPAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(IPAddressAvailabilityResult, self).__init__(**kwargs)
self.available = kwargs.get('available', None)
self.available_ip_addresses = kwargs.get('available_ip_addresses', None)
class IpAllocation(Resource):
"""IpAllocation resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar subnet: The Subnet that using the prefix of this IpAllocation resource.
:vartype subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar virtual_network: The VirtualNetwork that using the prefix of this IpAllocation resource.
:vartype virtual_network: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param type_properties_type: The type for the IpAllocation. Possible values include:
"Undefined", "Hypernet".
:type type_properties_type: str or ~azure.mgmt.network.v2020_04_01.models.IpAllocationType
:param prefix: The address prefix for the IpAllocation.
:type prefix: str
:param prefix_length: The address prefix length for the IpAllocation.
:type prefix_length: int
:param prefix_type: The address prefix Type for the IpAllocation. Possible values include:
"IPv4", "IPv6".
:type prefix_type: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
:param ipam_allocation_id: The IPAM allocation ID.
:type ipam_allocation_id: str
:param allocation_tags: IpAllocation tags.
:type allocation_tags: dict[str, str]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'subnet': {'readonly': True},
'virtual_network': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'virtual_network': {'key': 'properties.virtualNetwork', 'type': 'SubResource'},
'type_properties_type': {'key': 'properties.type', 'type': 'str'},
'prefix': {'key': 'properties.prefix', 'type': 'str'},
'prefix_length': {'key': 'properties.prefixLength', 'type': 'int'},
'prefix_type': {'key': 'properties.prefixType', 'type': 'str'},
'ipam_allocation_id': {'key': 'properties.ipamAllocationId', 'type': 'str'},
'allocation_tags': {'key': 'properties.allocationTags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(IpAllocation, self).__init__(**kwargs)
self.etag = None
self.subnet = None
self.virtual_network = None
self.type_properties_type = kwargs.get('type_properties_type', None)
self.prefix = kwargs.get('prefix', None)
self.prefix_length = kwargs.get('prefix_length', 0)
self.prefix_type = kwargs.get('prefix_type', None)
self.ipam_allocation_id = kwargs.get('ipam_allocation_id', None)
self.allocation_tags = kwargs.get('allocation_tags', None)
class IpAllocationListResult(msrest.serialization.Model):
"""Response for the ListIpAllocations API service call.
:param value: A list of IpAllocation resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.IpAllocation]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[IpAllocation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpAllocationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class IPConfiguration(SubResource):
"""IP configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param subnet: The reference to the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:param public_ip_address: The reference to the public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.PublicIPAddress
:ivar provisioning_state: The provisioning state of the IP configuration resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
class IPConfigurationBgpPeeringAddress(msrest.serialization.Model):
"""Properties of IPConfigurationBgpPeeringAddress.
Variables are only populated by the server, and will be ignored when sending a request.
:param ipconfiguration_id: The ID of IP configuration which belongs to gateway.
:type ipconfiguration_id: str
:ivar default_bgp_ip_addresses: The list of default BGP peering addresses which belong to IP
configuration.
:vartype default_bgp_ip_addresses: list[str]
:param custom_bgp_ip_addresses: The list of custom BGP peering addresses which belong to IP
configuration.
:type custom_bgp_ip_addresses: list[str]
:ivar tunnel_ip_addresses: The list of tunnel public IP addresses which belong to IP
configuration.
:vartype tunnel_ip_addresses: list[str]
"""
_validation = {
'default_bgp_ip_addresses': {'readonly': True},
'tunnel_ip_addresses': {'readonly': True},
}
_attribute_map = {
'ipconfiguration_id': {'key': 'ipconfigurationId', 'type': 'str'},
'default_bgp_ip_addresses': {'key': 'defaultBgpIpAddresses', 'type': '[str]'},
'custom_bgp_ip_addresses': {'key': 'customBgpIpAddresses', 'type': '[str]'},
'tunnel_ip_addresses': {'key': 'tunnelIpAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(IPConfigurationBgpPeeringAddress, self).__init__(**kwargs)
self.ipconfiguration_id = kwargs.get('ipconfiguration_id', None)
self.default_bgp_ip_addresses = None
self.custom_bgp_ip_addresses = kwargs.get('custom_bgp_ip_addresses', None)
self.tunnel_ip_addresses = None
class IPConfigurationProfile(SubResource):
"""IP configuration profile child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param subnet: The reference to the subnet resource to create a container network interface ip
configuration.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:ivar provisioning_state: The provisioning state of the IP configuration profile resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IPConfigurationProfile, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.subnet = kwargs.get('subnet', None)
self.provisioning_state = None
class IpGroup(Resource):
"""The IpGroups resource information.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the IpGroups resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param ip_addresses: IpAddresses/IpAddressPrefixes in the IpGroups resource.
:type ip_addresses: list[str]
:ivar firewalls: List of references to Azure resources that this IpGroups is associated with.
:vartype firewalls: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'firewalls': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'ip_addresses': {'key': 'properties.ipAddresses', 'type': '[str]'},
'firewalls': {'key': 'properties.firewalls', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(IpGroup, self).__init__(**kwargs)
self.etag = None
self.provisioning_state = None
self.ip_addresses = kwargs.get('ip_addresses', None)
self.firewalls = None
class IpGroupListResult(msrest.serialization.Model):
"""Response for the ListIpGroups API service call.
:param value: The list of IpGroups information resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.IpGroup]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[IpGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class IpsecPolicy(msrest.serialization.Model):
"""An IPSec Policy configuration for a virtual network gateway connection.
All required parameters must be populated in order to send to Azure.
:param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) lifetime in seconds for a site to site VPN tunnel.
:type sa_life_time_seconds: int
:param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) payload size in KB for a site to site VPN tunnel.
:type sa_data_size_kilobytes: int
:param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible
values include: "None", "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES128", "GCMAES192",
"GCMAES256".
:type ipsec_encryption: str or ~azure.mgmt.network.v2020_04_01.models.IpsecEncryption
:param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values
include: "MD5", "SHA1", "SHA256", "GCMAES128", "GCMAES192", "GCMAES256".
:type ipsec_integrity: str or ~azure.mgmt.network.v2020_04_01.models.IpsecIntegrity
:param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values
include: "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES256", "GCMAES128".
:type ike_encryption: str or ~azure.mgmt.network.v2020_04_01.models.IkeEncryption
:param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values
include: "MD5", "SHA1", "SHA256", "SHA384", "GCMAES256", "GCMAES128".
:type ike_integrity: str or ~azure.mgmt.network.v2020_04_01.models.IkeIntegrity
:param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values
include: "None", "DHGroup1", "DHGroup2", "DHGroup14", "DHGroup2048", "ECP256", "ECP384",
"DHGroup24".
:type dh_group: str or ~azure.mgmt.network.v2020_04_01.models.DhGroup
:param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values
include: "None", "PFS1", "PFS2", "PFS2048", "ECP256", "ECP384", "PFS24", "PFS14", "PFSMM".
:type pfs_group: str or ~azure.mgmt.network.v2020_04_01.models.PfsGroup
"""
_validation = {
'sa_life_time_seconds': {'required': True},
'sa_data_size_kilobytes': {'required': True},
'ipsec_encryption': {'required': True},
'ipsec_integrity': {'required': True},
'ike_encryption': {'required': True},
'ike_integrity': {'required': True},
'dh_group': {'required': True},
'pfs_group': {'required': True},
}
_attribute_map = {
'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'},
'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'},
'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'},
'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'},
'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'},
'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'},
'dh_group': {'key': 'dhGroup', 'type': 'str'},
'pfs_group': {'key': 'pfsGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpsecPolicy, self).__init__(**kwargs)
self.sa_life_time_seconds = kwargs['sa_life_time_seconds']
self.sa_data_size_kilobytes = kwargs['sa_data_size_kilobytes']
self.ipsec_encryption = kwargs['ipsec_encryption']
self.ipsec_integrity = kwargs['ipsec_integrity']
self.ike_encryption = kwargs['ike_encryption']
self.ike_integrity = kwargs['ike_integrity']
self.dh_group = kwargs['dh_group']
self.pfs_group = kwargs['pfs_group']
class IpTag(msrest.serialization.Model):
"""Contains the IpTag associated with the object.
:param ip_tag_type: The IP tag type. Example: FirstPartyUsage.
:type ip_tag_type: str
:param tag: The value of the IP tag associated with the public IP. Example: SQL.
:type tag: str
"""
_attribute_map = {
'ip_tag_type': {'key': 'ipTagType', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpTag, self).__init__(**kwargs)
self.ip_tag_type = kwargs.get('ip_tag_type', None)
self.tag = kwargs.get('tag', None)
class Ipv6CircuitConnectionConfig(msrest.serialization.Model):
"""IPv6 Circuit Connection properties for global reach.
Variables are only populated by the server, and will be ignored when sending a request.
:param address_prefix: /125 IP address space to carve out customer addresses for global reach.
:type address_prefix: str
:ivar circuit_connection_status: Express Route Circuit connection state. Possible values
include: "Connected", "Connecting", "Disconnected".
:vartype circuit_connection_status: str or
~azure.mgmt.network.v2020_04_01.models.CircuitConnectionStatus
"""
_validation = {
'circuit_connection_status': {'readonly': True},
}
_attribute_map = {
'address_prefix': {'key': 'addressPrefix', 'type': 'str'},
'circuit_connection_status': {'key': 'circuitConnectionStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Ipv6CircuitConnectionConfig, self).__init__(**kwargs)
self.address_prefix = kwargs.get('address_prefix', None)
self.circuit_connection_status = None
class Ipv6ExpressRouteCircuitPeeringConfig(msrest.serialization.Model):
"""Contains IPv6 peering config.
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringConfig
:param route_filter: The reference to the RouteFilter resource.
:type route_filter: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param state: The state of peering. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeeringState
"""
_attribute_map = {
'primary_peer_address_prefix': {'key': 'primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'secondaryPeerAddressPrefix', 'type': 'str'},
'microsoft_peering_config': {'key': 'microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'route_filter': {'key': 'routeFilter', 'type': 'SubResource'},
'state': {'key': 'state', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Ipv6ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.route_filter = kwargs.get('route_filter', None)
self.state = kwargs.get('state', None)
class ListHubRouteTablesResult(msrest.serialization.Model):
"""List of RouteTables and a URL nextLink to get the next set of results.
:param value: List of RouteTables.
:type value: list[~azure.mgmt.network.v2020_04_01.models.HubRouteTable]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[HubRouteTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListHubRouteTablesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListHubVirtualNetworkConnectionsResult(msrest.serialization.Model):
"""List of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
:param value: List of HubVirtualNetworkConnections.
:type value: list[~azure.mgmt.network.v2020_04_01.models.HubVirtualNetworkConnection]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[HubVirtualNetworkConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListHubVirtualNetworkConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListP2SVpnGatewaysResult(msrest.serialization.Model):
"""Result of the request to list P2SVpnGateways. It contains a list of P2SVpnGateways and a URL nextLink to get the next set of results.
:param value: List of P2SVpnGateways.
:type value: list[~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[P2SVpnGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListP2SVpnGatewaysResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVirtualHubRouteTableV2SResult(msrest.serialization.Model):
"""List of VirtualHubRouteTableV2s and a URL nextLink to get the next set of results.
:param value: List of VirtualHubRouteTableV2s.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualHubRouteTableV2]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualHubRouteTableV2]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVirtualHubRouteTableV2SResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVirtualHubsResult(msrest.serialization.Model):
"""Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink to get the next set of results.
:param value: List of VirtualHubs.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualHub]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualHub]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVirtualHubsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVirtualWANsResult(msrest.serialization.Model):
"""Result of the request to list VirtualWANs. It contains a list of VirtualWANs and a URL nextLink to get the next set of results.
:param value: List of VirtualWANs.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualWAN]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualWAN]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVirtualWANsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnConnectionsResult(msrest.serialization.Model):
"""Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains a list of Vpn Connections and a URL nextLink to get the next set of results.
:param value: List of Vpn Connections.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnConnection]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnGatewaysResult(msrest.serialization.Model):
"""Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink to get the next set of results.
:param value: List of VpnGateways.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnGateway]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnGatewaysResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnServerConfigurationsResult(msrest.serialization.Model):
"""Result of the request to list all VpnServerConfigurations. It contains a list of VpnServerConfigurations and a URL nextLink to get the next set of results.
:param value: List of VpnServerConfigurations.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnServerConfiguration]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnServerConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnServerConfigurationsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnSiteLinkConnectionsResult(msrest.serialization.Model):
"""Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains a list of Vpn Connections and a URL nextLink to get the next set of results.
:param value: List of VpnSiteLinkConnections.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnSiteLinkConnection]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnSiteLinkConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnSiteLinkConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnSiteLinksResult(msrest.serialization.Model):
"""Result of the request to list VpnSiteLinks. It contains a list of VpnSiteLinks and a URL nextLink to get the next set of results.
:param value: List of VpnSitesLinks.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnSiteLink]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnSiteLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnSiteLinksResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnSitesResult(msrest.serialization.Model):
"""Result of the request to list VpnSites. It contains a list of VpnSites and a URL nextLink to get the next set of results.
:param value: List of VpnSites.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnSite]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnSite]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnSitesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class LoadBalancer(Resource):
"""LoadBalancer resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The load balancer SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.LoadBalancerSku
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param frontend_ip_configurations: Object representing the frontend IPs to be used for the load
balancer.
:type frontend_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.FrontendIPConfiguration]
:param backend_address_pools: Collection of backend address pools used by a load balancer.
:type backend_address_pools: list[~azure.mgmt.network.v2020_04_01.models.BackendAddressPool]
:param load_balancing_rules: Object collection representing the load balancing rules Gets the
provisioning.
:type load_balancing_rules: list[~azure.mgmt.network.v2020_04_01.models.LoadBalancingRule]
:param probes: Collection of probe objects used in the load balancer.
:type probes: list[~azure.mgmt.network.v2020_04_01.models.Probe]
:param inbound_nat_rules: Collection of inbound NAT Rules used by a load balancer. Defining
inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT
pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are
associated with individual virtual machines cannot reference an Inbound NAT pool. They have to
reference individual inbound NAT rules.
:type inbound_nat_rules: list[~azure.mgmt.network.v2020_04_01.models.InboundNatRule]
:param inbound_nat_pools: Defines an external port range for inbound NAT to a single backend
port on NICs associated with a load balancer. Inbound NAT rules are created automatically for
each NIC associated with the Load Balancer using an external port from this range. Defining an
Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules.
Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with
individual virtual machines cannot reference an inbound NAT pool. They have to reference
individual inbound NAT rules.
:type inbound_nat_pools: list[~azure.mgmt.network.v2020_04_01.models.InboundNatPool]
:param outbound_rules: The outbound rules.
:type outbound_rules: list[~azure.mgmt.network.v2020_04_01.models.OutboundRule]
:ivar resource_guid: The resource GUID property of the load balancer resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the load balancer resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'LoadBalancerSku'},
'etag': {'key': 'etag', 'type': 'str'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[FrontendIPConfiguration]'},
'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[LoadBalancingRule]'},
'probes': {'key': 'properties.probes', 'type': '[Probe]'},
'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[InboundNatRule]'},
'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[InboundNatPool]'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[OutboundRule]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancer, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = None
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
self.load_balancing_rules = kwargs.get('load_balancing_rules', None)
self.probes = kwargs.get('probes', None)
self.inbound_nat_rules = kwargs.get('inbound_nat_rules', None)
self.inbound_nat_pools = kwargs.get('inbound_nat_pools', None)
self.outbound_rules = kwargs.get('outbound_rules', None)
self.resource_guid = None
self.provisioning_state = None
class LoadBalancerBackendAddress(msrest.serialization.Model):
"""Load balancer backend addresses.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Name of the backend address.
:type name: str
:param virtual_network: Reference to an existing virtual network.
:type virtual_network: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param ip_address: IP Address belonging to the referenced virtual network.
:type ip_address: str
:ivar network_interface_ip_configuration: Reference to IP address defined in network
interfaces.
:vartype network_interface_ip_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_validation = {
'network_interface_ip_configuration': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'virtual_network': {'key': 'properties.virtualNetwork', 'type': 'SubResource'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'network_interface_ip_configuration': {'key': 'properties.networkInterfaceIPConfiguration', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerBackendAddress, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.virtual_network = kwargs.get('virtual_network', None)
self.ip_address = kwargs.get('ip_address', None)
self.network_interface_ip_configuration = None
class LoadBalancerBackendAddressPoolListResult(msrest.serialization.Model):
"""Response for ListBackendAddressPool API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of backend address pools in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.BackendAddressPool]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[BackendAddressPool]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerBackendAddressPoolListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerFrontendIPConfigurationListResult(msrest.serialization.Model):
"""Response for ListFrontendIPConfiguration API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of frontend IP configurations in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.FrontendIPConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[FrontendIPConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerFrontendIPConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerListResult(msrest.serialization.Model):
"""Response for ListLoadBalancers API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancers in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.LoadBalancer]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancer]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerLoadBalancingRuleListResult(msrest.serialization.Model):
"""Response for ListLoadBalancingRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancing rules in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.LoadBalancingRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancingRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerLoadBalancingRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerOutboundRuleListResult(msrest.serialization.Model):
"""Response for ListOutboundRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of outbound rules in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.OutboundRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[OutboundRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerOutboundRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerProbeListResult(msrest.serialization.Model):
"""Response for ListProbe API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of probes in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.Probe]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[Probe]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerProbeListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerSku(msrest.serialization.Model):
"""SKU of a load balancer.
:param name: Name of a load balancer SKU. Possible values include: "Basic", "Standard".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.LoadBalancerSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class LoadBalancingRule(SubResource):
"""A load balancing rule for a load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of load balancing rules
used by the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param backend_address_pool: A reference to a pool of DIPs. Inbound traffic is randomly load
balanced across IPs in the backend IPs.
:type backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param probe: The reference to the load balancer probe used by the load balancing rule.
:type probe: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param protocol: The reference to the transport protocol used by the load balancing rule.
Possible values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.TransportProtocol
:param load_distribution: The load distribution policy for this rule. Possible values include:
"Default", "SourceIP", "SourceIPProtocol".
:type load_distribution: str or ~azure.mgmt.network.v2020_04_01.models.LoadDistribution
:param frontend_port: The port for the external endpoint. Port numbers for each rule must be
unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0
enables "Any Port".
:type frontend_port: int
:param backend_port: The port used for internal connections on the endpoint. Acceptable values
are between 0 and 65535. Note that value 0 enables "Any Port".
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param disable_outbound_snat: Configures SNAT for the VMs in the backend pool to use the
publicIP address specified in the frontend of the load balancing rule.
:type disable_outbound_snat: bool
:ivar provisioning_state: The provisioning state of the load balancing rule resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'probe': {'key': 'properties.probe', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'load_distribution': {'key': 'properties.loadDistribution', 'type': 'str'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'disable_outbound_snat': {'key': 'properties.disableOutboundSnat', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancingRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.probe = kwargs.get('probe', None)
self.protocol = kwargs.get('protocol', None)
self.load_distribution = kwargs.get('load_distribution', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.disable_outbound_snat = kwargs.get('disable_outbound_snat', None)
self.provisioning_state = None
class LocalNetworkGateway(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param local_network_address_space: Local network site address space.
:type local_network_address_space: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param gateway_ip_address: IP address of local network gateway.
:type gateway_ip_address: str
:param fqdn: FQDN of local network gateway.
:type fqdn: str
:param bgp_settings: Local network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2020_04_01.models.BgpSettings
:ivar resource_guid: The resource GUID property of the local network gateway resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the local network gateway resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'local_network_address_space': {'key': 'properties.localNetworkAddressSpace', 'type': 'AddressSpace'},
'gateway_ip_address': {'key': 'properties.gatewayIpAddress', 'type': 'str'},
'fqdn': {'key': 'properties.fqdn', 'type': 'str'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LocalNetworkGateway, self).__init__(**kwargs)
self.etag = None
self.local_network_address_space = kwargs.get('local_network_address_space', None)
self.gateway_ip_address = kwargs.get('gateway_ip_address', None)
self.fqdn = kwargs.get('fqdn', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.resource_guid = None
self.provisioning_state = None
class LocalNetworkGatewayListResult(msrest.serialization.Model):
"""Response for ListLocalNetworkGateways API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of local network gateways that exists in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.LocalNetworkGateway]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LocalNetworkGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LocalNetworkGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LogSpecification(msrest.serialization.Model):
"""Description of logging specification.
:param name: The name of the specification.
:type name: str
:param display_name: The display name of the specification.
:type display_name: str
:param blob_duration: Duration of the blob.
:type blob_duration: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'blob_duration': {'key': 'blobDuration', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LogSpecification, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.blob_duration = kwargs.get('blob_duration', None)
class ManagedRuleGroupOverride(msrest.serialization.Model):
"""Defines a managed rule group override setting.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The managed rule group to override.
:type rule_group_name: str
:param rules: List of rules that will be disabled. If none specified, all rules in the group
will be disabled.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.ManagedRuleOverride]
"""
_validation = {
'rule_group_name': {'required': True},
}
_attribute_map = {
'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'},
'rules': {'key': 'rules', 'type': '[ManagedRuleOverride]'},
}
def __init__(
self,
**kwargs
):
super(ManagedRuleGroupOverride, self).__init__(**kwargs)
self.rule_group_name = kwargs['rule_group_name']
self.rules = kwargs.get('rules', None)
class ManagedRuleOverride(msrest.serialization.Model):
"""Defines a managed rule group override setting.
All required parameters must be populated in order to send to Azure.
:param rule_id: Required. Identifier for the managed rule.
:type rule_id: str
:param state: The state of the managed rule. Defaults to Disabled if not specified. Possible
values include: "Disabled".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.ManagedRuleEnabledState
"""
_validation = {
'rule_id': {'required': True},
}
_attribute_map = {
'rule_id': {'key': 'ruleId', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ManagedRuleOverride, self).__init__(**kwargs)
self.rule_id = kwargs['rule_id']
self.state = kwargs.get('state', None)
class ManagedRulesDefinition(msrest.serialization.Model):
"""Allow to exclude some variable satisfy the condition for the WAF check.
All required parameters must be populated in order to send to Azure.
:param exclusions: The Exclusions that are applied on the policy.
:type exclusions: list[~azure.mgmt.network.v2020_04_01.models.OwaspCrsExclusionEntry]
:param managed_rule_sets: Required. The managed rule sets that are associated with the policy.
:type managed_rule_sets: list[~azure.mgmt.network.v2020_04_01.models.ManagedRuleSet]
"""
_validation = {
'managed_rule_sets': {'required': True},
}
_attribute_map = {
'exclusions': {'key': 'exclusions', 'type': '[OwaspCrsExclusionEntry]'},
'managed_rule_sets': {'key': 'managedRuleSets', 'type': '[ManagedRuleSet]'},
}
def __init__(
self,
**kwargs
):
super(ManagedRulesDefinition, self).__init__(**kwargs)
self.exclusions = kwargs.get('exclusions', None)
self.managed_rule_sets = kwargs['managed_rule_sets']
class ManagedRuleSet(msrest.serialization.Model):
"""Defines a managed rule set.
All required parameters must be populated in order to send to Azure.
:param rule_set_type: Required. Defines the rule set type to use.
:type rule_set_type: str
:param rule_set_version: Required. Defines the version of the rule set to use.
:type rule_set_version: str
:param rule_group_overrides: Defines the rule group overrides to apply to the rule set.
:type rule_group_overrides:
list[~azure.mgmt.network.v2020_04_01.models.ManagedRuleGroupOverride]
"""
_validation = {
'rule_set_type': {'required': True},
'rule_set_version': {'required': True},
}
_attribute_map = {
'rule_set_type': {'key': 'ruleSetType', 'type': 'str'},
'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'},
'rule_group_overrides': {'key': 'ruleGroupOverrides', 'type': '[ManagedRuleGroupOverride]'},
}
def __init__(
self,
**kwargs
):
super(ManagedRuleSet, self).__init__(**kwargs)
self.rule_set_type = kwargs['rule_set_type']
self.rule_set_version = kwargs['rule_set_version']
self.rule_group_overrides = kwargs.get('rule_group_overrides', None)
class ManagedServiceIdentity(msrest.serialization.Model):
"""Identity for the resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of the system assigned identity. This property will only
be provided for a system assigned identity.
:vartype principal_id: str
:ivar tenant_id: The tenant id of the system assigned identity. This property will only be
provided for a system assigned identity.
:vartype tenant_id: str
:param type: The type of identity used for the resource. The type 'SystemAssigned,
UserAssigned' includes both an implicitly created identity and a set of user assigned
identities. The type 'None' will remove any identities from the virtual machine. Possible
values include: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", "None".
:type type: str or ~azure.mgmt.network.v2020_04_01.models.ResourceIdentityType
:param user_assigned_identities: The list of user identities associated with resource. The user
identity dictionary key references will be ARM resource ids in the form:
'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
:type user_assigned_identities: dict[str,
~azure.mgmt.network.v2020_04_01.models.Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties]
"""
_validation = {
'principal_id': {'readonly': True},
'tenant_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties}'},
}
def __init__(
self,
**kwargs
):
super(ManagedServiceIdentity, self).__init__(**kwargs)
self.principal_id = None
self.tenant_id = None
self.type = kwargs.get('type', None)
self.user_assigned_identities = kwargs.get('user_assigned_identities', None)
class MatchCondition(msrest.serialization.Model):
"""Define match conditions.
All required parameters must be populated in order to send to Azure.
:param match_variables: Required. List of match variables.
:type match_variables: list[~azure.mgmt.network.v2020_04_01.models.MatchVariable]
:param operator: Required. The operator to be matched. Possible values include: "IPMatch",
"Equal", "Contains", "LessThan", "GreaterThan", "LessThanOrEqual", "GreaterThanOrEqual",
"BeginsWith", "EndsWith", "Regex", "GeoMatch".
:type operator: str or ~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallOperator
:param negation_conditon: Whether this is negate condition or not.
:type negation_conditon: bool
:param match_values: Required. Match value.
:type match_values: list[str]
:param transforms: List of transforms.
:type transforms: list[str or
~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallTransform]
"""
_validation = {
'match_variables': {'required': True},
'operator': {'required': True},
'match_values': {'required': True},
}
_attribute_map = {
'match_variables': {'key': 'matchVariables', 'type': '[MatchVariable]'},
'operator': {'key': 'operator', 'type': 'str'},
'negation_conditon': {'key': 'negationConditon', 'type': 'bool'},
'match_values': {'key': 'matchValues', 'type': '[str]'},
'transforms': {'key': 'transforms', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(MatchCondition, self).__init__(**kwargs)
self.match_variables = kwargs['match_variables']
self.operator = kwargs['operator']
self.negation_conditon = kwargs.get('negation_conditon', None)
self.match_values = kwargs['match_values']
self.transforms = kwargs.get('transforms', None)
class MatchedRule(msrest.serialization.Model):
"""Matched rule.
:param rule_name: Name of the matched network security rule.
:type rule_name: str
:param action: The network traffic is allowed or denied. Possible values are 'Allow' and
'Deny'.
:type action: str
"""
_attribute_map = {
'rule_name': {'key': 'ruleName', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MatchedRule, self).__init__(**kwargs)
self.rule_name = kwargs.get('rule_name', None)
self.action = kwargs.get('action', None)
class MatchVariable(msrest.serialization.Model):
"""Define match variables.
All required parameters must be populated in order to send to Azure.
:param variable_name: Required. Match Variable. Possible values include: "RemoteAddr",
"RequestMethod", "QueryString", "PostArgs", "RequestUri", "RequestHeaders", "RequestBody",
"RequestCookies".
:type variable_name: str or
~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallMatchVariable
:param selector: The selector of match variable.
:type selector: str
"""
_validation = {
'variable_name': {'required': True},
}
_attribute_map = {
'variable_name': {'key': 'variableName', 'type': 'str'},
'selector': {'key': 'selector', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MatchVariable, self).__init__(**kwargs)
self.variable_name = kwargs['variable_name']
self.selector = kwargs.get('selector', None)
class MetricSpecification(msrest.serialization.Model):
"""Description of metrics specification.
:param name: The name of the metric.
:type name: str
:param display_name: The display name of the metric.
:type display_name: str
:param display_description: The description of the metric.
:type display_description: str
:param unit: Units the metric to be displayed in.
:type unit: str
:param aggregation_type: The aggregation type.
:type aggregation_type: str
:param availabilities: List of availability.
:type availabilities: list[~azure.mgmt.network.v2020_04_01.models.Availability]
:param enable_regional_mdm_account: Whether regional MDM account enabled.
:type enable_regional_mdm_account: bool
:param fill_gap_with_zero: Whether gaps would be filled with zeros.
:type fill_gap_with_zero: bool
:param metric_filter_pattern: Pattern for the filter of the metric.
:type metric_filter_pattern: str
:param dimensions: List of dimensions.
:type dimensions: list[~azure.mgmt.network.v2020_04_01.models.Dimension]
:param is_internal: Whether the metric is internal.
:type is_internal: bool
:param source_mdm_account: The source MDM account.
:type source_mdm_account: str
:param source_mdm_namespace: The source MDM namespace.
:type source_mdm_namespace: str
:param resource_id_dimension_name_override: The resource Id dimension name override.
:type resource_id_dimension_name_override: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'display_description': {'key': 'displayDescription', 'type': 'str'},
'unit': {'key': 'unit', 'type': 'str'},
'aggregation_type': {'key': 'aggregationType', 'type': 'str'},
'availabilities': {'key': 'availabilities', 'type': '[Availability]'},
'enable_regional_mdm_account': {'key': 'enableRegionalMdmAccount', 'type': 'bool'},
'fill_gap_with_zero': {'key': 'fillGapWithZero', 'type': 'bool'},
'metric_filter_pattern': {'key': 'metricFilterPattern', 'type': 'str'},
'dimensions': {'key': 'dimensions', 'type': '[Dimension]'},
'is_internal': {'key': 'isInternal', 'type': 'bool'},
'source_mdm_account': {'key': 'sourceMdmAccount', 'type': 'str'},
'source_mdm_namespace': {'key': 'sourceMdmNamespace', 'type': 'str'},
'resource_id_dimension_name_override': {'key': 'resourceIdDimensionNameOverride', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MetricSpecification, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.display_description = kwargs.get('display_description', None)
self.unit = kwargs.get('unit', None)
self.aggregation_type = kwargs.get('aggregation_type', None)
self.availabilities = kwargs.get('availabilities', None)
self.enable_regional_mdm_account = kwargs.get('enable_regional_mdm_account', None)
self.fill_gap_with_zero = kwargs.get('fill_gap_with_zero', None)
self.metric_filter_pattern = kwargs.get('metric_filter_pattern', None)
self.dimensions = kwargs.get('dimensions', None)
self.is_internal = kwargs.get('is_internal', None)
self.source_mdm_account = kwargs.get('source_mdm_account', None)
self.source_mdm_namespace = kwargs.get('source_mdm_namespace', None)
self.resource_id_dimension_name_override = kwargs.get('resource_id_dimension_name_override', None)
class NatGateway(Resource):
"""Nat Gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The nat gateway SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.NatGatewaySku
:param zones: A list of availability zones denoting the zone in which Nat Gateway should be
deployed.
:type zones: list[str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param idle_timeout_in_minutes: The idle timeout of the nat gateway.
:type idle_timeout_in_minutes: int
:param public_ip_addresses: An array of public ip addresses associated with the nat gateway
resource.
:type public_ip_addresses: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param public_ip_prefixes: An array of public ip prefixes associated with the nat gateway
resource.
:type public_ip_prefixes: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar subnets: An array of references to the subnets using this nat gateway resource.
:vartype subnets: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar resource_guid: The resource GUID property of the NAT gateway resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the NAT gateway resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'subnets': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'NatGatewaySku'},
'zones': {'key': 'zones', 'type': '[str]'},
'etag': {'key': 'etag', 'type': 'str'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'public_ip_addresses': {'key': 'properties.publicIpAddresses', 'type': '[SubResource]'},
'public_ip_prefixes': {'key': 'properties.publicIpPrefixes', 'type': '[SubResource]'},
'subnets': {'key': 'properties.subnets', 'type': '[SubResource]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGateway, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.zones = kwargs.get('zones', None)
self.etag = None
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.public_ip_addresses = kwargs.get('public_ip_addresses', None)
self.public_ip_prefixes = kwargs.get('public_ip_prefixes', None)
self.subnets = None
self.resource_guid = None
self.provisioning_state = None
class NatGatewayListResult(msrest.serialization.Model):
"""Response for ListNatGateways API service call.
:param value: A list of Nat Gateways that exists in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NatGateway]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NatGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NatGatewaySku(msrest.serialization.Model):
"""SKU of nat gateway.
:param name: Name of Nat Gateway SKU. Possible values include: "Standard".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.NatGatewaySkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class NatRuleCondition(FirewallPolicyRuleCondition):
"""Rule condition of type nat.
All required parameters must be populated in order to send to Azure.
:param name: Name of the rule condition.
:type name: str
:param description: Description of the rule condition.
:type description: str
:param rule_condition_type: Required. Rule Condition Type.Constant filled by server. Possible
values include: "ApplicationRuleCondition", "NetworkRuleCondition", "NatRuleCondition".
:type rule_condition_type: str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionType
:param ip_protocols: Array of FirewallPolicyRuleConditionNetworkProtocols.
:type ip_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionNetworkProtocol]
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses or Service Tags.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
"""
_validation = {
'rule_condition_type': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rule_condition_type': {'key': 'ruleConditionType', 'type': 'str'},
'ip_protocols': {'key': 'ipProtocols', 'type': '[str]'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(NatRuleCondition, self).__init__(**kwargs)
self.rule_condition_type = 'NatRuleCondition' # type: str
self.ip_protocols = kwargs.get('ip_protocols', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
class NetworkConfigurationDiagnosticParameters(msrest.serialization.Model):
"""Parameters to get network configuration diagnostic.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the target resource to perform network
configuration diagnostic. Valid options are VM, NetworkInterface, VMSS/NetworkInterface and
Application Gateway.
:type target_resource_id: str
:param verbosity_level: Verbosity level. Possible values include: "Normal", "Minimum", "Full".
:type verbosity_level: str or ~azure.mgmt.network.v2020_04_01.models.VerbosityLevel
:param profiles: Required. List of network configuration diagnostic profiles.
:type profiles:
list[~azure.mgmt.network.v2020_04_01.models.NetworkConfigurationDiagnosticProfile]
"""
_validation = {
'target_resource_id': {'required': True},
'profiles': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'verbosity_level': {'key': 'verbosityLevel', 'type': 'str'},
'profiles': {'key': 'profiles', 'type': '[NetworkConfigurationDiagnosticProfile]'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.verbosity_level = kwargs.get('verbosity_level', None)
self.profiles = kwargs['profiles']
class NetworkConfigurationDiagnosticProfile(msrest.serialization.Model):
"""Parameters to compare with network configuration.
All required parameters must be populated in order to send to Azure.
:param direction: Required. The direction of the traffic. Possible values include: "Inbound",
"Outbound".
:type direction: str or ~azure.mgmt.network.v2020_04_01.models.Direction
:param protocol: Required. Protocol to be verified on. Accepted values are '*', TCP, UDP.
:type protocol: str
:param source: Required. Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag.
:type source: str
:param destination: Required. Traffic destination. Accepted values are: '*', IP Address/CIDR,
Service Tag.
:type destination: str
:param destination_port: Required. Traffic destination port. Accepted values are '*' and a
single port in the range (0 - 65535).
:type destination_port: str
"""
_validation = {
'direction': {'required': True},
'protocol': {'required': True},
'source': {'required': True},
'destination': {'required': True},
'destination_port': {'required': True},
}
_attribute_map = {
'direction': {'key': 'direction', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'},
'destination': {'key': 'destination', 'type': 'str'},
'destination_port': {'key': 'destinationPort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticProfile, self).__init__(**kwargs)
self.direction = kwargs['direction']
self.protocol = kwargs['protocol']
self.source = kwargs['source']
self.destination = kwargs['destination']
self.destination_port = kwargs['destination_port']
class NetworkConfigurationDiagnosticResponse(msrest.serialization.Model):
"""Results of network configuration diagnostic on the target resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar results: List of network configuration diagnostic results.
:vartype results:
list[~azure.mgmt.network.v2020_04_01.models.NetworkConfigurationDiagnosticResult]
"""
_validation = {
'results': {'readonly': True},
}
_attribute_map = {
'results': {'key': 'results', 'type': '[NetworkConfigurationDiagnosticResult]'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticResponse, self).__init__(**kwargs)
self.results = None
class NetworkConfigurationDiagnosticResult(msrest.serialization.Model):
"""Network configuration diagnostic result corresponded to provided traffic query.
:param profile: Network configuration diagnostic profile.
:type profile: ~azure.mgmt.network.v2020_04_01.models.NetworkConfigurationDiagnosticProfile
:param network_security_group_result: Network security group result.
:type network_security_group_result:
~azure.mgmt.network.v2020_04_01.models.NetworkSecurityGroupResult
"""
_attribute_map = {
'profile': {'key': 'profile', 'type': 'NetworkConfigurationDiagnosticProfile'},
'network_security_group_result': {'key': 'networkSecurityGroupResult', 'type': 'NetworkSecurityGroupResult'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticResult, self).__init__(**kwargs)
self.profile = kwargs.get('profile', None)
self.network_security_group_result = kwargs.get('network_security_group_result', None)
class NetworkIntentPolicy(Resource):
"""Network Intent Policy resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkIntentPolicy, self).__init__(**kwargs)
self.etag = None
class NetworkIntentPolicyConfiguration(msrest.serialization.Model):
"""Details of NetworkIntentPolicyConfiguration for PrepareNetworkPoliciesRequest.
:param network_intent_policy_name: The name of the Network Intent Policy for storing in target
subscription.
:type network_intent_policy_name: str
:param source_network_intent_policy: Source network intent policy.
:type source_network_intent_policy: ~azure.mgmt.network.v2020_04_01.models.NetworkIntentPolicy
"""
_attribute_map = {
'network_intent_policy_name': {'key': 'networkIntentPolicyName', 'type': 'str'},
'source_network_intent_policy': {'key': 'sourceNetworkIntentPolicy', 'type': 'NetworkIntentPolicy'},
}
def __init__(
self,
**kwargs
):
super(NetworkIntentPolicyConfiguration, self).__init__(**kwargs)
self.network_intent_policy_name = kwargs.get('network_intent_policy_name', None)
self.source_network_intent_policy = kwargs.get('source_network_intent_policy', None)
class NetworkInterface(Resource):
"""A network interface in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar virtual_machine: The reference to a virtual machine.
:vartype virtual_machine: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param network_security_group: The reference to the NetworkSecurityGroup resource.
:type network_security_group: ~azure.mgmt.network.v2020_04_01.models.NetworkSecurityGroup
:ivar private_endpoint: A reference to the private endpoint to which the network interface is
linked.
:vartype private_endpoint: ~azure.mgmt.network.v2020_04_01.models.PrivateEndpoint
:param ip_configurations: A list of IPConfigurations of the network interface.
:type ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration]
:ivar tap_configurations: A list of TapConfigurations of the network interface.
:vartype tap_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceTapConfiguration]
:param dns_settings: The DNS settings in network interface.
:type dns_settings: ~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceDnsSettings
:ivar mac_address: The MAC address of the network interface.
:vartype mac_address: str
:ivar primary: Whether this is a primary network interface on a virtual machine.
:vartype primary: bool
:param enable_accelerated_networking: If the network interface is accelerated networking
enabled.
:type enable_accelerated_networking: bool
:param enable_ip_forwarding: Indicates whether IP forwarding is enabled on this network
interface.
:type enable_ip_forwarding: bool
:ivar hosted_workloads: A list of references to linked BareMetal resources.
:vartype hosted_workloads: list[str]
:ivar resource_guid: The resource GUID property of the network interface resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the network interface resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_machine': {'readonly': True},
'private_endpoint': {'readonly': True},
'tap_configurations': {'readonly': True},
'mac_address': {'readonly': True},
'primary': {'readonly': True},
'hosted_workloads': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_machine': {'key': 'properties.virtualMachine', 'type': 'SubResource'},
'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'tap_configurations': {'key': 'properties.tapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'},
'dns_settings': {'key': 'properties.dnsSettings', 'type': 'NetworkInterfaceDnsSettings'},
'mac_address': {'key': 'properties.macAddress', 'type': 'str'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'enable_accelerated_networking': {'key': 'properties.enableAcceleratedNetworking', 'type': 'bool'},
'enable_ip_forwarding': {'key': 'properties.enableIPForwarding', 'type': 'bool'},
'hosted_workloads': {'key': 'properties.hostedWorkloads', 'type': '[str]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterface, self).__init__(**kwargs)
self.etag = None
self.virtual_machine = None
self.network_security_group = kwargs.get('network_security_group', None)
self.private_endpoint = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.tap_configurations = None
self.dns_settings = kwargs.get('dns_settings', None)
self.mac_address = None
self.primary = None
self.enable_accelerated_networking = kwargs.get('enable_accelerated_networking', None)
self.enable_ip_forwarding = kwargs.get('enable_ip_forwarding', None)
self.hosted_workloads = None
self.resource_guid = None
self.provisioning_state = None
class NetworkInterfaceAssociation(msrest.serialization.Model):
"""Network interface and its custom security rules.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Network interface ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
class NetworkInterfaceDnsSettings(msrest.serialization.Model):
"""DNS settings of a network interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param dns_servers: List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure
provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be
the only value in dnsServers collection.
:type dns_servers: list[str]
:ivar applied_dns_servers: If the VM that uses this NIC is part of an Availability Set, then
this list will have the union of all DNS servers from all NICs that are part of the
Availability Set. This property is what is configured on each of those VMs.
:vartype applied_dns_servers: list[str]
:param internal_dns_name_label: Relative DNS name for this NIC used for internal communications
between VMs in the same virtual network.
:type internal_dns_name_label: str
:ivar internal_fqdn: Fully qualified DNS name supporting internal communications between VMs in
the same virtual network.
:vartype internal_fqdn: str
:ivar internal_domain_name_suffix: Even if internalDnsNameLabel is not specified, a DNS entry
is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the
VM name with the value of internalDomainNameSuffix.
:vartype internal_domain_name_suffix: str
"""
_validation = {
'applied_dns_servers': {'readonly': True},
'internal_fqdn': {'readonly': True},
'internal_domain_name_suffix': {'readonly': True},
}
_attribute_map = {
'dns_servers': {'key': 'dnsServers', 'type': '[str]'},
'applied_dns_servers': {'key': 'appliedDnsServers', 'type': '[str]'},
'internal_dns_name_label': {'key': 'internalDnsNameLabel', 'type': 'str'},
'internal_fqdn': {'key': 'internalFqdn', 'type': 'str'},
'internal_domain_name_suffix': {'key': 'internalDomainNameSuffix', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceDnsSettings, self).__init__(**kwargs)
self.dns_servers = kwargs.get('dns_servers', None)
self.applied_dns_servers = None
self.internal_dns_name_label = kwargs.get('internal_dns_name_label', None)
self.internal_fqdn = None
self.internal_domain_name_suffix = None
class NetworkInterfaceIPConfiguration(SubResource):
"""IPConfiguration in a network interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_network_taps: The reference to Virtual Network Taps.
:type virtual_network_taps: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkTap]
:param application_gateway_backend_address_pools: The reference to
ApplicationGatewayBackendAddressPool resource.
:type application_gateway_backend_address_pools:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationGatewayBackendAddressPool]
:param load_balancer_backend_address_pools: The reference to LoadBalancerBackendAddressPool
resource.
:type load_balancer_backend_address_pools:
list[~azure.mgmt.network.v2020_04_01.models.BackendAddressPool]
:param load_balancer_inbound_nat_rules: A list of references of LoadBalancerInboundNatRules.
:type load_balancer_inbound_nat_rules:
list[~azure.mgmt.network.v2020_04_01.models.InboundNatRule]
:param private_ip_address: Private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param private_ip_address_version: Whether the specific IP configuration is IPv4 or IPv6.
Default is IPv4. Possible values include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
:param subnet: Subnet bound to the IP configuration.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:param primary: Whether this is a primary customer address on the network interface.
:type primary: bool
:param public_ip_address: Public IP address bound to the IP configuration.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.PublicIPAddress
:param application_security_groups: Application security groups in which the IP configuration
is included.
:type application_security_groups:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationSecurityGroup]
:ivar provisioning_state: The provisioning state of the network interface IP configuration.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar private_link_connection_properties: PrivateLinkConnection properties for the network
interface.
:vartype private_link_connection_properties:
~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'private_link_connection_properties': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_network_taps': {'key': 'properties.virtualNetworkTaps', 'type': '[VirtualNetworkTap]'},
'application_gateway_backend_address_pools': {'key': 'properties.applicationGatewayBackendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'},
'load_balancer_backend_address_pools': {'key': 'properties.loadBalancerBackendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancer_inbound_nat_rules': {'key': 'properties.loadBalancerInboundNatRules', 'type': '[InboundNatRule]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'application_security_groups': {'key': 'properties.applicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_link_connection_properties': {'key': 'properties.privateLinkConnectionProperties', 'type': 'NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.virtual_network_taps = kwargs.get('virtual_network_taps', None)
self.application_gateway_backend_address_pools = kwargs.get('application_gateway_backend_address_pools', None)
self.load_balancer_backend_address_pools = kwargs.get('load_balancer_backend_address_pools', None)
self.load_balancer_inbound_nat_rules = kwargs.get('load_balancer_inbound_nat_rules', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
self.subnet = kwargs.get('subnet', None)
self.primary = kwargs.get('primary', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.application_security_groups = kwargs.get('application_security_groups', None)
self.provisioning_state = None
self.private_link_connection_properties = None
class NetworkInterfaceIPConfigurationListResult(msrest.serialization.Model):
"""Response for list ip configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ip configurations.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterfaceIPConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceIPConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties(msrest.serialization.Model):
"""PrivateLinkConnection properties for the network interface.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar group_id: The group ID for current private link connection.
:vartype group_id: str
:ivar required_member_name: The required member name for current private link connection.
:vartype required_member_name: str
:ivar fqdns: List of FQDNs for current private link connection.
:vartype fqdns: list[str]
"""
_validation = {
'group_id': {'readonly': True},
'required_member_name': {'readonly': True},
'fqdns': {'readonly': True},
}
_attribute_map = {
'group_id': {'key': 'groupId', 'type': 'str'},
'required_member_name': {'key': 'requiredMemberName', 'type': 'str'},
'fqdns': {'key': 'fqdns', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties, self).__init__(**kwargs)
self.group_id = None
self.required_member_name = None
self.fqdns = None
class NetworkInterfaceListResult(msrest.serialization.Model):
"""Response for the ListNetworkInterface API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of network interfaces in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterface]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterface]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceLoadBalancerListResult(msrest.serialization.Model):
"""Response for list ip configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancers.
:type value: list[~azure.mgmt.network.v2020_04_01.models.LoadBalancer]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancer]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceLoadBalancerListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceTapConfiguration(SubResource):
"""Tap configuration in a Network Interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Sub Resource type.
:vartype type: str
:param virtual_network_tap: The reference to the Virtual Network Tap resource.
:type virtual_network_tap: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkTap
:ivar provisioning_state: The provisioning state of the network interface tap configuration
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'virtual_network_tap': {'key': 'properties.virtualNetworkTap', 'type': 'VirtualNetworkTap'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceTapConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.virtual_network_tap = kwargs.get('virtual_network_tap', None)
self.provisioning_state = None
class NetworkInterfaceTapConfigurationListResult(msrest.serialization.Model):
"""Response for list tap configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of tap configurations.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceTapConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterfaceTapConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceTapConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkProfile(Resource):
"""Network profile resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar container_network_interfaces: List of child container network interfaces.
:vartype container_network_interfaces:
list[~azure.mgmt.network.v2020_04_01.models.ContainerNetworkInterface]
:param container_network_interface_configurations: List of chid container network interface
configurations.
:type container_network_interface_configurations:
list[~azure.mgmt.network.v2020_04_01.models.ContainerNetworkInterfaceConfiguration]
:ivar resource_guid: The resource GUID property of the network profile resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the network profile resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'container_network_interfaces': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[ContainerNetworkInterface]'},
'container_network_interface_configurations': {'key': 'properties.containerNetworkInterfaceConfigurations', 'type': '[ContainerNetworkInterfaceConfiguration]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkProfile, self).__init__(**kwargs)
self.etag = None
self.container_network_interfaces = None
self.container_network_interface_configurations = kwargs.get('container_network_interface_configurations', None)
self.resource_guid = None
self.provisioning_state = None
class NetworkProfileListResult(msrest.serialization.Model):
"""Response for ListNetworkProfiles API service call.
:param value: A list of network profiles that exist in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkProfile]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkProfile]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkProfileListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NetworkRuleCondition(FirewallPolicyRuleCondition):
"""Rule condition of type network.
All required parameters must be populated in order to send to Azure.
:param name: Name of the rule condition.
:type name: str
:param description: Description of the rule condition.
:type description: str
:param rule_condition_type: Required. Rule Condition Type.Constant filled by server. Possible
values include: "ApplicationRuleCondition", "NetworkRuleCondition", "NatRuleCondition".
:type rule_condition_type: str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionType
:param ip_protocols: Array of FirewallPolicyRuleConditionNetworkProtocols.
:type ip_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.FirewallPolicyRuleConditionNetworkProtocol]
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses or Service Tags.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param source_ip_groups: List of source IpGroups for this rule.
:type source_ip_groups: list[str]
:param destination_ip_groups: List of destination IpGroups for this rule.
:type destination_ip_groups: list[str]
"""
_validation = {
'rule_condition_type': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rule_condition_type': {'key': 'ruleConditionType', 'type': 'str'},
'ip_protocols': {'key': 'ipProtocols', 'type': '[str]'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
'source_ip_groups': {'key': 'sourceIpGroups', 'type': '[str]'},
'destination_ip_groups': {'key': 'destinationIpGroups', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(NetworkRuleCondition, self).__init__(**kwargs)
self.rule_condition_type = 'NetworkRuleCondition' # type: str
self.ip_protocols = kwargs.get('ip_protocols', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
self.source_ip_groups = kwargs.get('source_ip_groups', None)
self.destination_ip_groups = kwargs.get('destination_ip_groups', None)
class NetworkSecurityGroup(Resource):
"""NetworkSecurityGroup resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param security_rules: A collection of security rules of the network security group.
:type security_rules: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
:ivar default_security_rules: The default security rules of network security group.
:vartype default_security_rules: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
:ivar network_interfaces: A collection of references to network interfaces.
:vartype network_interfaces: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterface]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2020_04_01.models.Subnet]
:ivar flow_logs: A collection of references to flow log resources.
:vartype flow_logs: list[~azure.mgmt.network.v2020_04_01.models.FlowLog]
:ivar resource_guid: The resource GUID property of the network security group resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the network security group resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'default_security_rules': {'readonly': True},
'network_interfaces': {'readonly': True},
'subnets': {'readonly': True},
'flow_logs': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'security_rules': {'key': 'properties.securityRules', 'type': '[SecurityRule]'},
'default_security_rules': {'key': 'properties.defaultSecurityRules', 'type': '[SecurityRule]'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'flow_logs': {'key': 'properties.flowLogs', 'type': '[FlowLog]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroup, self).__init__(**kwargs)
self.etag = None
self.security_rules = kwargs.get('security_rules', None)
self.default_security_rules = None
self.network_interfaces = None
self.subnets = None
self.flow_logs = None
self.resource_guid = None
self.provisioning_state = None
class NetworkSecurityGroupListResult(msrest.serialization.Model):
"""Response for ListNetworkSecurityGroups API service call.
:param value: A list of NetworkSecurityGroup resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkSecurityGroup]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NetworkSecurityGroupResult(msrest.serialization.Model):
"""Network configuration diagnostic result corresponded provided traffic query.
Variables are only populated by the server, and will be ignored when sending a request.
:param security_rule_access_result: The network traffic is allowed or denied. Possible values
include: "Allow", "Deny".
:type security_rule_access_result: str or
~azure.mgmt.network.v2020_04_01.models.SecurityRuleAccess
:ivar evaluated_network_security_groups: List of results network security groups diagnostic.
:vartype evaluated_network_security_groups:
list[~azure.mgmt.network.v2020_04_01.models.EvaluatedNetworkSecurityGroup]
"""
_validation = {
'evaluated_network_security_groups': {'readonly': True},
}
_attribute_map = {
'security_rule_access_result': {'key': 'securityRuleAccessResult', 'type': 'str'},
'evaluated_network_security_groups': {'key': 'evaluatedNetworkSecurityGroups', 'type': '[EvaluatedNetworkSecurityGroup]'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroupResult, self).__init__(**kwargs)
self.security_rule_access_result = kwargs.get('security_rule_access_result', None)
self.evaluated_network_security_groups = None
class NetworkSecurityRulesEvaluationResult(msrest.serialization.Model):
"""Network security rules evaluation result.
:param name: Name of the network security rule.
:type name: str
:param protocol_matched: Value indicating whether protocol is matched.
:type protocol_matched: bool
:param source_matched: Value indicating whether source is matched.
:type source_matched: bool
:param source_port_matched: Value indicating whether source port is matched.
:type source_port_matched: bool
:param destination_matched: Value indicating whether destination is matched.
:type destination_matched: bool
:param destination_port_matched: Value indicating whether destination port is matched.
:type destination_port_matched: bool
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'protocol_matched': {'key': 'protocolMatched', 'type': 'bool'},
'source_matched': {'key': 'sourceMatched', 'type': 'bool'},
'source_port_matched': {'key': 'sourcePortMatched', 'type': 'bool'},
'destination_matched': {'key': 'destinationMatched', 'type': 'bool'},
'destination_port_matched': {'key': 'destinationPortMatched', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityRulesEvaluationResult, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.protocol_matched = kwargs.get('protocol_matched', None)
self.source_matched = kwargs.get('source_matched', None)
self.source_port_matched = kwargs.get('source_port_matched', None)
self.destination_matched = kwargs.get('destination_matched', None)
self.destination_port_matched = kwargs.get('destination_port_matched', None)
class NetworkVirtualAppliance(Resource):
"""NetworkVirtualAppliance Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param identity: The service principal that has read access to cloud-init and config blob.
:type identity: ~azure.mgmt.network.v2020_04_01.models.ManagedServiceIdentity
:param sku: Network Virtual Appliance SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.VirtualApplianceSkuProperties
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param boot_strap_configuration_blob: BootStrapConfigurationBlob storage URLs.
:type boot_strap_configuration_blob: list[str]
:param virtual_hub: The Virtual Hub where Network Virtual Appliance is being deployed.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param cloud_init_configuration_blob: CloudInitConfigurationBlob storage URLs.
:type cloud_init_configuration_blob: list[str]
:param virtual_appliance_asn: VirtualAppliance ASN.
:type virtual_appliance_asn: long
:ivar virtual_appliance_nics: List of Virtual Appliance Network Interfaces.
:vartype virtual_appliance_nics:
list[~azure.mgmt.network.v2020_04_01.models.VirtualApplianceNicProperties]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_appliance_asn': {'maximum': 4294967295, 'minimum': 0},
'virtual_appliance_nics': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'identity': {'key': 'identity', 'type': 'ManagedServiceIdentity'},
'sku': {'key': 'sku', 'type': 'VirtualApplianceSkuProperties'},
'etag': {'key': 'etag', 'type': 'str'},
'boot_strap_configuration_blob': {'key': 'properties.bootStrapConfigurationBlob', 'type': '[str]'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'cloud_init_configuration_blob': {'key': 'properties.cloudInitConfigurationBlob', 'type': '[str]'},
'virtual_appliance_asn': {'key': 'properties.virtualApplianceAsn', 'type': 'long'},
'virtual_appliance_nics': {'key': 'properties.virtualApplianceNics', 'type': '[VirtualApplianceNicProperties]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkVirtualAppliance, self).__init__(**kwargs)
self.identity = kwargs.get('identity', None)
self.sku = kwargs.get('sku', None)
self.etag = None
self.boot_strap_configuration_blob = kwargs.get('boot_strap_configuration_blob', None)
self.virtual_hub = kwargs.get('virtual_hub', None)
self.cloud_init_configuration_blob = kwargs.get('cloud_init_configuration_blob', None)
self.virtual_appliance_asn = kwargs.get('virtual_appliance_asn', None)
self.virtual_appliance_nics = None
self.provisioning_state = None
class NetworkVirtualApplianceListResult(msrest.serialization.Model):
"""Response for ListNetworkVirtualAppliances API service call.
:param value: List of Network Virtual Appliances.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkVirtualAppliance]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkVirtualAppliance]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkVirtualApplianceListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NetworkWatcher(Resource):
"""Network watcher in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the network watcher resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkWatcher, self).__init__(**kwargs)
self.etag = None
self.provisioning_state = None
class NetworkWatcherListResult(msrest.serialization.Model):
"""Response for ListNetworkWatchers API service call.
:param value: List of network watcher resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.NetworkWatcher]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkWatcher]'},
}
def __init__(
self,
**kwargs
):
super(NetworkWatcherListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class NextHopParameters(msrest.serialization.Model):
"""Parameters that define the source and destination endpoint.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The resource identifier of the target resource against
which the action is to be performed.
:type target_resource_id: str
:param source_ip_address: Required. The source IP address.
:type source_ip_address: str
:param destination_ip_address: Required. The destination IP address.
:type destination_ip_address: str
:param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is
enabled on any of the nics, then this parameter must be specified. Otherwise optional).
:type target_nic_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
'source_ip_address': {'required': True},
'destination_ip_address': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'source_ip_address': {'key': 'sourceIPAddress', 'type': 'str'},
'destination_ip_address': {'key': 'destinationIPAddress', 'type': 'str'},
'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NextHopParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.source_ip_address = kwargs['source_ip_address']
self.destination_ip_address = kwargs['destination_ip_address']
self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None)
class NextHopResult(msrest.serialization.Model):
"""The information about next hop from the specified VM.
:param next_hop_type: Next hop type. Possible values include: "Internet", "VirtualAppliance",
"VirtualNetworkGateway", "VnetLocal", "HyperNetGateway", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2020_04_01.models.NextHopType
:param next_hop_ip_address: Next hop IP Address.
:type next_hop_ip_address: str
:param route_table_id: The resource identifier for the route table associated with the route
being returned. If the route being returned does not correspond to any user created routes then
this field will be the string 'System Route'.
:type route_table_id: str
"""
_attribute_map = {
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
'route_table_id': {'key': 'routeTableId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NextHopResult, self).__init__(**kwargs)
self.next_hop_type = kwargs.get('next_hop_type', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.route_table_id = kwargs.get('route_table_id', None)
class Operation(msrest.serialization.Model):
"""Network REST API operation definition.
:param name: Operation name: {provider}/{resource}/{operation}.
:type name: str
:param display: Display metadata associated with the operation.
:type display: ~azure.mgmt.network.v2020_04_01.models.OperationDisplay
:param origin: Origin of the operation.
:type origin: str
:param service_specification: Specification of the service.
:type service_specification:
~azure.mgmt.network.v2020_04_01.models.OperationPropertiesFormatServiceSpecification
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplay'},
'origin': {'key': 'origin', 'type': 'str'},
'service_specification': {'key': 'properties.serviceSpecification', 'type': 'OperationPropertiesFormatServiceSpecification'},
}
def __init__(
self,
**kwargs
):
super(Operation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display = kwargs.get('display', None)
self.origin = kwargs.get('origin', None)
self.service_specification = kwargs.get('service_specification', None)
class OperationDisplay(msrest.serialization.Model):
"""Display metadata associated with the operation.
:param provider: Service provider: Microsoft Network.
:type provider: str
:param resource: Resource on which the operation is performed.
:type resource: str
:param operation: Type of the operation: get, read, delete, etc.
:type operation: str
:param description: Description of the operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.resource = kwargs.get('resource', None)
self.operation = kwargs.get('operation', None)
self.description = kwargs.get('description', None)
class OperationListResult(msrest.serialization.Model):
"""Result of the request to list Network operations. It contains a list of operations and a URL link to get the next set of results.
:param value: List of Network operations supported by the Network resource provider.
:type value: list[~azure.mgmt.network.v2020_04_01.models.Operation]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class OperationPropertiesFormatServiceSpecification(msrest.serialization.Model):
"""Specification of the service.
:param metric_specifications: Operation service specification.
:type metric_specifications: list[~azure.mgmt.network.v2020_04_01.models.MetricSpecification]
:param log_specifications: Operation log specification.
:type log_specifications: list[~azure.mgmt.network.v2020_04_01.models.LogSpecification]
"""
_attribute_map = {
'metric_specifications': {'key': 'metricSpecifications', 'type': '[MetricSpecification]'},
'log_specifications': {'key': 'logSpecifications', 'type': '[LogSpecification]'},
}
def __init__(
self,
**kwargs
):
super(OperationPropertiesFormatServiceSpecification, self).__init__(**kwargs)
self.metric_specifications = kwargs.get('metric_specifications', None)
self.log_specifications = kwargs.get('log_specifications', None)
class OutboundRule(SubResource):
"""Outbound rule of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of outbound rules used by
the load balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param allocated_outbound_ports: The number of outbound ports to be used for NAT.
:type allocated_outbound_ports: int
:param frontend_ip_configurations: The Frontend IP addresses of the load balancer.
:type frontend_ip_configurations: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param backend_address_pool: A reference to a pool of DIPs. Outbound traffic is randomly load
balanced across IPs in the backend IPs.
:type backend_address_pool: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the outbound rule resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param protocol: The protocol for the outbound rule in load balancer. Possible values include:
"Tcp", "Udp", "All".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.LoadBalancerOutboundRuleProtocol
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param idle_timeout_in_minutes: The timeout for the TCP idle connection.
:type idle_timeout_in_minutes: int
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'allocated_outbound_ports': {'key': 'properties.allocatedOutboundPorts', 'type': 'int'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[SubResource]'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(OutboundRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.allocated_outbound_ports = kwargs.get('allocated_outbound_ports', None)
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.provisioning_state = None
self.protocol = kwargs.get('protocol', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
class OwaspCrsExclusionEntry(msrest.serialization.Model):
"""Allow to exclude some variable satisfy the condition for the WAF check.
All required parameters must be populated in order to send to Azure.
:param match_variable: Required. The variable to be excluded. Possible values include:
"RequestHeaderNames", "RequestCookieNames", "RequestArgNames".
:type match_variable: str or
~azure.mgmt.network.v2020_04_01.models.OwaspCrsExclusionEntryMatchVariable
:param selector_match_operator: Required. When matchVariable is a collection, operate on the
selector to specify which elements in the collection this exclusion applies to. Possible values
include: "Equals", "Contains", "StartsWith", "EndsWith", "EqualsAny".
:type selector_match_operator: str or
~azure.mgmt.network.v2020_04_01.models.OwaspCrsExclusionEntrySelectorMatchOperator
:param selector: Required. When matchVariable is a collection, operator used to specify which
elements in the collection this exclusion applies to.
:type selector: str
"""
_validation = {
'match_variable': {'required': True},
'selector_match_operator': {'required': True},
'selector': {'required': True},
}
_attribute_map = {
'match_variable': {'key': 'matchVariable', 'type': 'str'},
'selector_match_operator': {'key': 'selectorMatchOperator', 'type': 'str'},
'selector': {'key': 'selector', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OwaspCrsExclusionEntry, self).__init__(**kwargs)
self.match_variable = kwargs['match_variable']
self.selector_match_operator = kwargs['selector_match_operator']
self.selector = kwargs['selector']
class P2SConnectionConfiguration(SubResource):
"""P2SConnectionConfiguration Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param vpn_client_address_pool: The reference to the address space resource which represents
Address space for P2S VpnClient.
:type vpn_client_address_pool: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param routing_configuration: The Routing Configuration indicating the associated and
propagated route tables on this connection.
:type routing_configuration: ~azure.mgmt.network.v2020_04_01.models.RoutingConfiguration
:ivar provisioning_state: The provisioning state of the P2SConnectionConfiguration resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'vpn_client_address_pool': {'key': 'properties.vpnClientAddressPool', 'type': 'AddressSpace'},
'routing_configuration': {'key': 'properties.routingConfiguration', 'type': 'RoutingConfiguration'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SConnectionConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None)
self.routing_configuration = kwargs.get('routing_configuration', None)
self.provisioning_state = None
class P2SVpnConnectionHealth(msrest.serialization.Model):
"""P2S Vpn connection detailed health written to sas url.
:param sas_url: Returned sas url of the blob to which the p2s vpn connection detailed health
will be written.
:type sas_url: str
"""
_attribute_map = {
'sas_url': {'key': 'sasUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnConnectionHealth, self).__init__(**kwargs)
self.sas_url = kwargs.get('sas_url', None)
class P2SVpnConnectionHealthRequest(msrest.serialization.Model):
"""List of P2S Vpn connection health request.
:param vpn_user_names_filter: The list of p2s vpn user names whose p2s vpn connection detailed
health to retrieve for.
:type vpn_user_names_filter: list[str]
:param output_blob_sas_url: The sas-url to download the P2S Vpn connection health detail.
:type output_blob_sas_url: str
"""
_attribute_map = {
'vpn_user_names_filter': {'key': 'vpnUserNamesFilter', 'type': '[str]'},
'output_blob_sas_url': {'key': 'outputBlobSasUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnConnectionHealthRequest, self).__init__(**kwargs)
self.vpn_user_names_filter = kwargs.get('vpn_user_names_filter', None)
self.output_blob_sas_url = kwargs.get('output_blob_sas_url', None)
class P2SVpnConnectionRequest(msrest.serialization.Model):
"""List of p2s vpn connections to be disconnected.
:param vpn_connection_ids: List of p2s vpn connection Ids.
:type vpn_connection_ids: list[str]
"""
_attribute_map = {
'vpn_connection_ids': {'key': 'vpnConnectionIds', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnConnectionRequest, self).__init__(**kwargs)
self.vpn_connection_ids = kwargs.get('vpn_connection_ids', None)
class P2SVpnGateway(Resource):
"""P2SVpnGateway Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_hub: The VirtualHub to which the gateway belongs.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param p2_s_connection_configurations: List of all p2s connection configurations of the
gateway.
:type p2_s_connection_configurations:
list[~azure.mgmt.network.v2020_04_01.models.P2SConnectionConfiguration]
:ivar provisioning_state: The provisioning state of the P2S VPN gateway resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param vpn_gateway_scale_unit: The scale unit for this p2s vpn gateway.
:type vpn_gateway_scale_unit: int
:param vpn_server_configuration: The VpnServerConfiguration to which the p2sVpnGateway is
attached to.
:type vpn_server_configuration: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar vpn_client_connection_health: All P2S VPN clients' connection health status.
:vartype vpn_client_connection_health:
~azure.mgmt.network.v2020_04_01.models.VpnClientConnectionHealth
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'vpn_client_connection_health': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'p2_s_connection_configurations': {'key': 'properties.p2SConnectionConfigurations', 'type': '[P2SConnectionConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'},
'vpn_server_configuration': {'key': 'properties.vpnServerConfiguration', 'type': 'SubResource'},
'vpn_client_connection_health': {'key': 'properties.vpnClientConnectionHealth', 'type': 'VpnClientConnectionHealth'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnGateway, self).__init__(**kwargs)
self.etag = None
self.virtual_hub = kwargs.get('virtual_hub', None)
self.p2_s_connection_configurations = kwargs.get('p2_s_connection_configurations', None)
self.provisioning_state = None
self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None)
self.vpn_server_configuration = kwargs.get('vpn_server_configuration', None)
self.vpn_client_connection_health = None
class P2SVpnProfileParameters(msrest.serialization.Model):
"""Vpn Client Parameters for package generation.
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2020_04_01.models.AuthenticationMethod
"""
_attribute_map = {
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnProfileParameters, self).__init__(**kwargs)
self.authentication_method = kwargs.get('authentication_method', None)
class PacketCapture(msrest.serialization.Model):
"""Parameters that define the create packet capture operation.
All required parameters must be populated in order to send to Azure.
:param target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. The storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2020_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2020_04_01.models.PacketCaptureFilter]
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
}
_attribute_map = {
'target': {'key': 'properties.target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'},
}
def __init__(
self,
**kwargs
):
super(PacketCapture, self).__init__(**kwargs)
self.target = kwargs['target']
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs['storage_location']
self.filters = kwargs.get('filters', None)
class PacketCaptureFilter(msrest.serialization.Model):
"""Filter that is applied to packet capture request. Multiple filters can be applied.
:param protocol: Protocol to be filtered on. Possible values include: "TCP", "UDP", "Any".
Default value: "Any".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.PcProtocol
:param local_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single
address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries.
Multiple ranges not currently supported. Mixing ranges with multiple entries not currently
supported. Default = null.
:type local_ip_address: str
:param remote_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single
address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries.
Multiple ranges not currently supported. Mixing ranges with multiple entries not currently
supported. Default = null.
:type remote_ip_address: str
:param local_port: Local port to be filtered on. Notation: "80" for single port entry."80-85"
for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing
ranges with multiple entries not currently supported. Default = null.
:type local_port: str
:param remote_port: Remote port to be filtered on. Notation: "80" for single port entry."80-85"
for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing
ranges with multiple entries not currently supported. Default = null.
:type remote_port: str
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'local_ip_address': {'key': 'localIPAddress', 'type': 'str'},
'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'},
'local_port': {'key': 'localPort', 'type': 'str'},
'remote_port': {'key': 'remotePort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureFilter, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', "Any")
self.local_ip_address = kwargs.get('local_ip_address', None)
self.remote_ip_address = kwargs.get('remote_ip_address', None)
self.local_port = kwargs.get('local_port', None)
self.remote_port = kwargs.get('remote_port', None)
class PacketCaptureListResult(msrest.serialization.Model):
"""List of packet capture sessions.
:param value: Information about packet capture sessions.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PacketCaptureResult]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PacketCaptureResult]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class PacketCaptureParameters(msrest.serialization.Model):
"""Parameters that define the create packet capture operation.
All required parameters must be populated in order to send to Azure.
:param target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. The storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2020_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2020_04_01.models.PacketCaptureFilter]
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
}
_attribute_map = {
'target': {'key': 'target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureParameters, self).__init__(**kwargs)
self.target = kwargs['target']
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs['storage_location']
self.filters = kwargs.get('filters', None)
class PacketCaptureQueryStatusResult(msrest.serialization.Model):
"""Status of packet capture session.
:param name: The name of the packet capture resource.
:type name: str
:param id: The ID of the packet capture resource.
:type id: str
:param capture_start_time: The start time of the packet capture session.
:type capture_start_time: ~datetime.datetime
:param packet_capture_status: The status of the packet capture session. Possible values
include: "NotStarted", "Running", "Stopped", "Error", "Unknown".
:type packet_capture_status: str or ~azure.mgmt.network.v2020_04_01.models.PcStatus
:param stop_reason: The reason the current packet capture session was stopped.
:type stop_reason: str
:param packet_capture_error: List of errors of packet capture session.
:type packet_capture_error: list[str or ~azure.mgmt.network.v2020_04_01.models.PcError]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'capture_start_time': {'key': 'captureStartTime', 'type': 'iso-8601'},
'packet_capture_status': {'key': 'packetCaptureStatus', 'type': 'str'},
'stop_reason': {'key': 'stopReason', 'type': 'str'},
'packet_capture_error': {'key': 'packetCaptureError', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureQueryStatusResult, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.capture_start_time = kwargs.get('capture_start_time', None)
self.packet_capture_status = kwargs.get('packet_capture_status', None)
self.stop_reason = kwargs.get('stop_reason', None)
self.packet_capture_error = kwargs.get('packet_capture_error', None)
class PacketCaptureResult(msrest.serialization.Model):
"""Information about packet capture session.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the packet capture session.
:vartype name: str
:ivar id: ID of the packet capture operation.
:vartype id: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param target: The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: The storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2020_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2020_04_01.models.PacketCaptureFilter]
:ivar provisioning_state: The provisioning state of the packet capture session. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'target': {'key': 'properties.target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.etag = None
self.target = kwargs.get('target', None)
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs.get('storage_location', None)
self.filters = kwargs.get('filters', None)
self.provisioning_state = None
class PacketCaptureResultProperties(PacketCaptureParameters):
"""The properties of a packet capture session.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. The storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2020_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2020_04_01.models.PacketCaptureFilter]
:ivar provisioning_state: The provisioning state of the packet capture session. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'target': {'key': 'target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureResultProperties, self).__init__(**kwargs)
self.provisioning_state = None
class PacketCaptureStorageLocation(msrest.serialization.Model):
"""The storage location for a packet capture session.
:param storage_id: The ID of the storage account to save the packet capture session. Required
if no local file path is provided.
:type storage_id: str
:param storage_path: The URI of the storage path to save the packet capture. Must be a
well-formed URI describing the location to save the packet capture.
:type storage_path: str
:param file_path: A valid local path on the targeting VM. Must include the name of the capture
file (*.cap). For linux virtual machine it must start with /var/captures. Required if no
storage ID is provided, otherwise optional.
:type file_path: str
"""
_attribute_map = {
'storage_id': {'key': 'storageId', 'type': 'str'},
'storage_path': {'key': 'storagePath', 'type': 'str'},
'file_path': {'key': 'filePath', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureStorageLocation, self).__init__(**kwargs)
self.storage_id = kwargs.get('storage_id', None)
self.storage_path = kwargs.get('storage_path', None)
self.file_path = kwargs.get('file_path', None)
class PatchRouteFilter(SubResource):
"""Route Filter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:vartype name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param rules: Collection of RouteFilterRules contained within a route filter.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.RouteFilterRule]
:ivar peerings: A collection of references to express route circuit peerings.
:vartype peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:ivar ipv6_peerings: A collection of references to express route circuit ipv6 peerings.
:vartype ipv6_peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the route filter resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'etag': {'readonly': True},
'type': {'readonly': True},
'peerings': {'readonly': True},
'ipv6_peerings': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PatchRouteFilter, self).__init__(**kwargs)
self.name = None
self.etag = None
self.type = None
self.tags = kwargs.get('tags', None)
self.rules = kwargs.get('rules', None)
self.peerings = None
self.ipv6_peerings = None
self.provisioning_state = None
class PatchRouteFilterRule(SubResource):
"""Route Filter Rule Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:vartype name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param access: The access type of the rule. Possible values include: "Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2020_04_01.models.Access
:param route_filter_rule_type: The rule type of the rule. Possible values include: "Community".
:type route_filter_rule_type: str or ~azure.mgmt.network.v2020_04_01.models.RouteFilterRuleType
:param communities: The collection for bgp community values to filter on. e.g.
['12076:5010','12076:5020'].
:type communities: list[str]
:ivar provisioning_state: The provisioning state of the route filter rule resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'},
'communities': {'key': 'properties.communities', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PatchRouteFilterRule, self).__init__(**kwargs)
self.name = None
self.etag = None
self.access = kwargs.get('access', None)
self.route_filter_rule_type = kwargs.get('route_filter_rule_type', None)
self.communities = kwargs.get('communities', None)
self.provisioning_state = None
class PeerExpressRouteCircuitConnection(SubResource):
"""Peer Express Route Circuit Connection in an ExpressRouteCircuitPeering resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the circuit.
:type express_route_circuit_peering: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the peered circuit.
:type peer_express_route_circuit_peering: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param address_prefix: /29 IP address space to carve out Customer addresses for tunnels.
:type address_prefix: str
:ivar circuit_connection_status: Express Route Circuit connection state. Possible values
include: "Connected", "Connecting", "Disconnected".
:vartype circuit_connection_status: str or
~azure.mgmt.network.v2020_04_01.models.CircuitConnectionStatus
:param connection_name: The name of the express route circuit connection resource.
:type connection_name: str
:param auth_resource_guid: The resource guid of the authorization used for the express route
circuit connection.
:type auth_resource_guid: str
:ivar provisioning_state: The provisioning state of the peer express route circuit connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'circuit_connection_status': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'},
'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'},
'connection_name': {'key': 'properties.connectionName', 'type': 'str'},
'auth_resource_guid': {'key': 'properties.authResourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PeerExpressRouteCircuitConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.circuit_connection_status = None
self.connection_name = kwargs.get('connection_name', None)
self.auth_resource_guid = kwargs.get('auth_resource_guid', None)
self.provisioning_state = None
class PeerExpressRouteCircuitConnectionListResult(msrest.serialization.Model):
"""Response for ListPeeredConnections API service call retrieves all global reach peer circuit connections that belongs to a Private Peering for an ExpressRouteCircuit.
:param value: The global reach peer circuit connection associated with Private Peering in an
ExpressRoute Circuit.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PeerExpressRouteCircuitConnection]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PeerExpressRouteCircuitConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PeerExpressRouteCircuitConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PolicySettings(msrest.serialization.Model):
"""Defines contents of a web application firewall global configuration.
:param state: The state of the policy. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallEnabledState
:param mode: The mode of the policy. Possible values include: "Prevention", "Detection".
:type mode: str or ~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallMode
:param request_body_check: Whether to allow WAF to check request Body.
:type request_body_check: bool
:param max_request_body_size_in_kb: Maximum request body size in Kb for WAF.
:type max_request_body_size_in_kb: int
:param file_upload_limit_in_mb: Maximum file upload size in Mb for WAF.
:type file_upload_limit_in_mb: int
"""
_validation = {
'max_request_body_size_in_kb': {'maximum': 128, 'minimum': 8},
'file_upload_limit_in_mb': {'minimum': 0},
}
_attribute_map = {
'state': {'key': 'state', 'type': 'str'},
'mode': {'key': 'mode', 'type': 'str'},
'request_body_check': {'key': 'requestBodyCheck', 'type': 'bool'},
'max_request_body_size_in_kb': {'key': 'maxRequestBodySizeInKb', 'type': 'int'},
'file_upload_limit_in_mb': {'key': 'fileUploadLimitInMb', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(PolicySettings, self).__init__(**kwargs)
self.state = kwargs.get('state', None)
self.mode = kwargs.get('mode', None)
self.request_body_check = kwargs.get('request_body_check', None)
self.max_request_body_size_in_kb = kwargs.get('max_request_body_size_in_kb', None)
self.file_upload_limit_in_mb = kwargs.get('file_upload_limit_in_mb', None)
class PrepareNetworkPoliciesRequest(msrest.serialization.Model):
"""Details of PrepareNetworkPolicies for Subnet.
:param service_name: The name of the service for which subnet is being prepared for.
:type service_name: str
:param network_intent_policy_configurations: A list of NetworkIntentPolicyConfiguration.
:type network_intent_policy_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkIntentPolicyConfiguration]
"""
_attribute_map = {
'service_name': {'key': 'serviceName', 'type': 'str'},
'network_intent_policy_configurations': {'key': 'networkIntentPolicyConfigurations', 'type': '[NetworkIntentPolicyConfiguration]'},
}
def __init__(
self,
**kwargs
):
super(PrepareNetworkPoliciesRequest, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.network_intent_policy_configurations = kwargs.get('network_intent_policy_configurations', None)
class PrivateDnsZoneConfig(msrest.serialization.Model):
"""PrivateDnsZoneConfig resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:param private_dns_zone_id: The resource id of the private dns zone.
:type private_dns_zone_id: str
:ivar record_sets: A collection of information regarding a recordSet, holding information to
identify private resources.
:vartype record_sets: list[~azure.mgmt.network.v2020_04_01.models.RecordSet]
"""
_validation = {
'record_sets': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'private_dns_zone_id': {'key': 'properties.privateDnsZoneId', 'type': 'str'},
'record_sets': {'key': 'properties.recordSets', 'type': '[RecordSet]'},
}
def __init__(
self,
**kwargs
):
super(PrivateDnsZoneConfig, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.private_dns_zone_id = kwargs.get('private_dns_zone_id', None)
self.record_sets = None
class PrivateDnsZoneGroup(SubResource):
"""Private dns zone group resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the private dns zone group resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_dns_zone_configs: A collection of private dns zone configurations of the private
dns zone group.
:type private_dns_zone_configs:
list[~azure.mgmt.network.v2020_04_01.models.PrivateDnsZoneConfig]
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_dns_zone_configs': {'key': 'properties.privateDnsZoneConfigs', 'type': '[PrivateDnsZoneConfig]'},
}
def __init__(
self,
**kwargs
):
super(PrivateDnsZoneGroup, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.provisioning_state = None
self.private_dns_zone_configs = kwargs.get('private_dns_zone_configs', None)
class PrivateDnsZoneGroupListResult(msrest.serialization.Model):
"""Response for the ListPrivateDnsZoneGroups API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of private dns zone group resources in a private endpoint.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PrivateDnsZoneGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateDnsZoneGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateDnsZoneGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class PrivateEndpoint(Resource):
"""Private endpoint resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param subnet: The ID of the subnet from which the private IP will be allocated.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:ivar network_interfaces: An array of references to the network interfaces created for this
private endpoint.
:vartype network_interfaces: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterface]
:ivar provisioning_state: The provisioning state of the private endpoint resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_link_service_connections: A grouping of information about the connection to the
remote resource.
:type private_link_service_connections:
list[~azure.mgmt.network.v2020_04_01.models.PrivateLinkServiceConnection]
:param manual_private_link_service_connections: A grouping of information about the connection
to the remote resource. Used when the network admin does not have access to approve connections
to the remote resource.
:type manual_private_link_service_connections:
list[~azure.mgmt.network.v2020_04_01.models.PrivateLinkServiceConnection]
:param custom_dns_configs: An array of custom dns configurations.
:type custom_dns_configs:
list[~azure.mgmt.network.v2020_04_01.models.CustomDnsConfigPropertiesFormat]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'network_interfaces': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_link_service_connections': {'key': 'properties.privateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'},
'manual_private_link_service_connections': {'key': 'properties.manualPrivateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'},
'custom_dns_configs': {'key': 'properties.customDnsConfigs', 'type': '[CustomDnsConfigPropertiesFormat]'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpoint, self).__init__(**kwargs)
self.etag = None
self.subnet = kwargs.get('subnet', None)
self.network_interfaces = None
self.provisioning_state = None
self.private_link_service_connections = kwargs.get('private_link_service_connections', None)
self.manual_private_link_service_connections = kwargs.get('manual_private_link_service_connections', None)
self.custom_dns_configs = kwargs.get('custom_dns_configs', None)
class PrivateEndpointConnection(SubResource):
"""PrivateEndpointConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar type: The resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar private_endpoint: The resource of private end point.
:vartype private_endpoint: ~azure.mgmt.network.v2020_04_01.models.PrivateEndpoint
:param private_link_service_connection_state: A collection of information about the state of
the connection between service consumer and provider.
:type private_link_service_connection_state:
~azure.mgmt.network.v2020_04_01.models.PrivateLinkServiceConnectionState
:ivar provisioning_state: The provisioning state of the private endpoint connection resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar link_identifier: The consumer link id.
:vartype link_identifier: str
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'private_endpoint': {'readonly': True},
'provisioning_state': {'readonly': True},
'link_identifier': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'link_identifier': {'key': 'properties.linkIdentifier', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpointConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.private_endpoint = None
self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None)
self.provisioning_state = None
self.link_identifier = None
class PrivateEndpointConnectionListResult(msrest.serialization.Model):
"""Response for the ListPrivateEndpointConnection API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of PrivateEndpointConnection resources for a specific private link
service.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PrivateEndpointConnection]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpointConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class PrivateEndpointListResult(msrest.serialization.Model):
"""Response for the ListPrivateEndpoints API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of private endpoint resources in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PrivateEndpoint]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateEndpoint]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpointListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class PrivateLinkService(Resource):
"""Private link service resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param load_balancer_frontend_ip_configurations: An array of references to the load balancer IP
configurations.
:type load_balancer_frontend_ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.FrontendIPConfiguration]
:param ip_configurations: An array of private link service IP configurations.
:type ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.PrivateLinkServiceIpConfiguration]
:ivar network_interfaces: An array of references to the network interfaces created for this
private link service.
:vartype network_interfaces: list[~azure.mgmt.network.v2020_04_01.models.NetworkInterface]
:ivar provisioning_state: The provisioning state of the private link service resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar private_endpoint_connections: An array of list about connections to the private endpoint.
:vartype private_endpoint_connections:
list[~azure.mgmt.network.v2020_04_01.models.PrivateEndpointConnection]
:param visibility: The visibility list of the private link service.
:type visibility: ~azure.mgmt.network.v2020_04_01.models.PrivateLinkServicePropertiesVisibility
:param auto_approval: The auto-approval list of the private link service.
:type auto_approval:
~azure.mgmt.network.v2020_04_01.models.PrivateLinkServicePropertiesAutoApproval
:param fqdns: The list of Fqdn.
:type fqdns: list[str]
:ivar alias: The alias of the private link service.
:vartype alias: str
:param enable_proxy_protocol: Whether the private link service is enabled for proxy protocol or
not.
:type enable_proxy_protocol: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'network_interfaces': {'readonly': True},
'provisioning_state': {'readonly': True},
'private_endpoint_connections': {'readonly': True},
'alias': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'load_balancer_frontend_ip_configurations': {'key': 'properties.loadBalancerFrontendIpConfigurations', 'type': '[FrontendIPConfiguration]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[PrivateLinkServiceIpConfiguration]'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[PrivateEndpointConnection]'},
'visibility': {'key': 'properties.visibility', 'type': 'PrivateLinkServicePropertiesVisibility'},
'auto_approval': {'key': 'properties.autoApproval', 'type': 'PrivateLinkServicePropertiesAutoApproval'},
'fqdns': {'key': 'properties.fqdns', 'type': '[str]'},
'alias': {'key': 'properties.alias', 'type': 'str'},
'enable_proxy_protocol': {'key': 'properties.enableProxyProtocol', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkService, self).__init__(**kwargs)
self.etag = None
self.load_balancer_frontend_ip_configurations = kwargs.get('load_balancer_frontend_ip_configurations', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.network_interfaces = None
self.provisioning_state = None
self.private_endpoint_connections = None
self.visibility = kwargs.get('visibility', None)
self.auto_approval = kwargs.get('auto_approval', None)
self.fqdns = kwargs.get('fqdns', None)
self.alias = None
self.enable_proxy_protocol = kwargs.get('enable_proxy_protocol', None)
class PrivateLinkServiceConnection(SubResource):
"""PrivateLinkServiceConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar type: The resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the private link service connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_link_service_id: The resource id of private link service.
:type private_link_service_id: str
:param group_ids: The ID(s) of the group(s) obtained from the remote resource that this private
endpoint should connect to.
:type group_ids: list[str]
:param request_message: A message passed to the owner of the remote resource with this
connection request. Restricted to 140 chars.
:type request_message: str
:param private_link_service_connection_state: A collection of read-only information about the
state of the connection to the remote resource.
:type private_link_service_connection_state:
~azure.mgmt.network.v2020_04_01.models.PrivateLinkServiceConnectionState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_link_service_id': {'key': 'properties.privateLinkServiceId', 'type': 'str'},
'group_ids': {'key': 'properties.groupIds', 'type': '[str]'},
'request_message': {'key': 'properties.requestMessage', 'type': 'str'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.provisioning_state = None
self.private_link_service_id = kwargs.get('private_link_service_id', None)
self.group_ids = kwargs.get('group_ids', None)
self.request_message = kwargs.get('request_message', None)
self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None)
class PrivateLinkServiceConnectionState(msrest.serialization.Model):
"""A collection of information about the state of the connection between service consumer and provider.
:param status: Indicates whether the connection has been Approved/Rejected/Removed by the owner
of the service.
:type status: str
:param description: The reason for approval/rejection of the connection.
:type description: str
:param actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:type actions_required: str
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'actions_required': {'key': 'actionsRequired', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceConnectionState, self).__init__(**kwargs)
self.status = kwargs.get('status', None)
self.description = kwargs.get('description', None)
self.actions_required = kwargs.get('actions_required', None)
class PrivateLinkServiceIpConfiguration(SubResource):
"""The private link service ip configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of private link service ip configuration.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: The resource type.
:vartype type: str
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param subnet: The reference to the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.Subnet
:param primary: Whether the ip configuration is primary or not.
:type primary: bool
:ivar provisioning_state: The provisioning state of the private link service IP configuration
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_ip_address_version: Whether the specific IP configuration is IPv4 or IPv6.
Default is IPv4. Possible values include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceIpConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.primary = kwargs.get('primary', None)
self.provisioning_state = None
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
class PrivateLinkServiceListResult(msrest.serialization.Model):
"""Response for the ListPrivateLinkService API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of PrivateLinkService resources in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PrivateLinkService]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateLinkService]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ResourceSet(msrest.serialization.Model):
"""The base resource set for visibility and auto-approval.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ResourceSet, self).__init__(**kwargs)
self.subscriptions = kwargs.get('subscriptions', None)
class PrivateLinkServicePropertiesAutoApproval(ResourceSet):
"""The auto-approval list of the private link service.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServicePropertiesAutoApproval, self).__init__(**kwargs)
class PrivateLinkServicePropertiesVisibility(ResourceSet):
"""The visibility list of the private link service.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServicePropertiesVisibility, self).__init__(**kwargs)
class PrivateLinkServiceVisibility(msrest.serialization.Model):
"""Response for the CheckPrivateLinkServiceVisibility API service call.
:param visible: Private Link Service Visibility (True/False).
:type visible: bool
"""
_attribute_map = {
'visible': {'key': 'visible', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceVisibility, self).__init__(**kwargs)
self.visible = kwargs.get('visible', None)
class Probe(SubResource):
"""A load balancer probe.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within the set of probes used by the load
balancer. This name can be used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:ivar load_balancing_rules: The load balancer rules that use this probe.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param protocol: The protocol of the end point. If 'Tcp' is specified, a received ACK is
required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response
from the specifies URI is required for the probe to be successful. Possible values include:
"Http", "Tcp", "Https".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.ProbeProtocol
:param port: The port for communicating the probe. Possible values range from 1 to 65535,
inclusive.
:type port: int
:param interval_in_seconds: The interval, in seconds, for how frequently to probe the endpoint
for health status. Typically, the interval is slightly less than half the allocated timeout
period (in seconds) which allows two full probes before taking the instance out of rotation.
The default value is 15, the minimum value is 5.
:type interval_in_seconds: int
:param number_of_probes: The number of probes where if no response, will result in stopping
further traffic from being delivered to the endpoint. This values allows endpoints to be taken
out of rotation faster or slower than the typical times used in Azure.
:type number_of_probes: int
:param request_path: The URI used for requesting health status from the VM. Path is required if
a protocol is set to http. Otherwise, it is not allowed. There is no default value.
:type request_path: str
:ivar provisioning_state: The provisioning state of the probe resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'load_balancing_rules': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'interval_in_seconds': {'key': 'properties.intervalInSeconds', 'type': 'int'},
'number_of_probes': {'key': 'properties.numberOfProbes', 'type': 'int'},
'request_path': {'key': 'properties.requestPath', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Probe, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.load_balancing_rules = None
self.protocol = kwargs.get('protocol', None)
self.port = kwargs.get('port', None)
self.interval_in_seconds = kwargs.get('interval_in_seconds', None)
self.number_of_probes = kwargs.get('number_of_probes', None)
self.request_path = kwargs.get('request_path', None)
self.provisioning_state = None
class PropagatedRouteTable(msrest.serialization.Model):
"""The list of RouteTables to advertise the routes to.
:param labels: The list of labels.
:type labels: list[str]
:param ids: The list of resource ids of all the RouteTables.
:type ids: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_attribute_map = {
'labels': {'key': 'labels', 'type': '[str]'},
'ids': {'key': 'ids', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(PropagatedRouteTable, self).__init__(**kwargs)
self.labels = kwargs.get('labels', None)
self.ids = kwargs.get('ids', None)
class ProtocolConfiguration(msrest.serialization.Model):
"""Configuration of the protocol.
:param http_configuration: HTTP configuration of the connectivity check.
:type http_configuration: ~azure.mgmt.network.v2020_04_01.models.HTTPConfiguration
"""
_attribute_map = {
'http_configuration': {'key': 'HTTPConfiguration', 'type': 'HTTPConfiguration'},
}
def __init__(
self,
**kwargs
):
super(ProtocolConfiguration, self).__init__(**kwargs)
self.http_configuration = kwargs.get('http_configuration', None)
class ProtocolCustomSettingsFormat(msrest.serialization.Model):
"""DDoS custom policy properties.
:param protocol: The protocol for which the DDoS protection policy is being customized.
Possible values include: "Tcp", "Udp", "Syn".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.DdosCustomPolicyProtocol
:param trigger_rate_override: The customized DDoS protection trigger rate.
:type trigger_rate_override: str
:param source_rate_override: The customized DDoS protection source rate.
:type source_rate_override: str
:param trigger_sensitivity_override: The customized DDoS protection trigger rate sensitivity
degrees. High: Trigger rate set with most sensitivity w.r.t. normal traffic. Default: Trigger
rate set with moderate sensitivity w.r.t. normal traffic. Low: Trigger rate set with less
sensitivity w.r.t. normal traffic. Relaxed: Trigger rate set with least sensitivity w.r.t.
normal traffic. Possible values include: "Relaxed", "Low", "Default", "High".
:type trigger_sensitivity_override: str or
~azure.mgmt.network.v2020_04_01.models.DdosCustomPolicyTriggerSensitivityOverride
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'trigger_rate_override': {'key': 'triggerRateOverride', 'type': 'str'},
'source_rate_override': {'key': 'sourceRateOverride', 'type': 'str'},
'trigger_sensitivity_override': {'key': 'triggerSensitivityOverride', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ProtocolCustomSettingsFormat, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', None)
self.trigger_rate_override = kwargs.get('trigger_rate_override', None)
self.source_rate_override = kwargs.get('source_rate_override', None)
self.trigger_sensitivity_override = kwargs.get('trigger_sensitivity_override', None)
class PublicIPAddress(Resource):
"""Public IP address resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The public IP address SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.PublicIPAddressSku
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:param public_ip_allocation_method: The public IP address allocation method. Possible values
include: "Static", "Dynamic".
:type public_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param public_ip_address_version: The public IP address version. Possible values include:
"IPv4", "IPv6".
:type public_ip_address_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
:ivar ip_configuration: The IP configuration associated with the public IP address.
:vartype ip_configuration: ~azure.mgmt.network.v2020_04_01.models.IPConfiguration
:param dns_settings: The FQDN of the DNS record associated with the public IP address.
:type dns_settings: ~azure.mgmt.network.v2020_04_01.models.PublicIPAddressDnsSettings
:param ddos_settings: The DDoS protection custom policy associated with the public IP address.
:type ddos_settings: ~azure.mgmt.network.v2020_04_01.models.DdosSettings
:param ip_tags: The list of tags associated with the public IP address.
:type ip_tags: list[~azure.mgmt.network.v2020_04_01.models.IpTag]
:param ip_address: The IP address associated with the public IP address resource.
:type ip_address: str
:param public_ip_prefix: The Public IP Prefix this Public IP Address should be allocated from.
:type public_ip_prefix: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param idle_timeout_in_minutes: The idle timeout of the public IP address.
:type idle_timeout_in_minutes: int
:ivar resource_guid: The resource GUID property of the public IP address resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the public IP address resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'ip_configuration': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'PublicIPAddressSku'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'public_ip_allocation_method': {'key': 'properties.publicIPAllocationMethod', 'type': 'str'},
'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'},
'ip_configuration': {'key': 'properties.ipConfiguration', 'type': 'IPConfiguration'},
'dns_settings': {'key': 'properties.dnsSettings', 'type': 'PublicIPAddressDnsSettings'},
'ddos_settings': {'key': 'properties.ddosSettings', 'type': 'DdosSettings'},
'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddress, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = None
self.zones = kwargs.get('zones', None)
self.public_ip_allocation_method = kwargs.get('public_ip_allocation_method', None)
self.public_ip_address_version = kwargs.get('public_ip_address_version', None)
self.ip_configuration = None
self.dns_settings = kwargs.get('dns_settings', None)
self.ddos_settings = kwargs.get('ddos_settings', None)
self.ip_tags = kwargs.get('ip_tags', None)
self.ip_address = kwargs.get('ip_address', None)
self.public_ip_prefix = kwargs.get('public_ip_prefix', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.resource_guid = None
self.provisioning_state = None
class PublicIPAddressDnsSettings(msrest.serialization.Model):
"""Contains FQDN of the DNS record associated with the public IP address.
:param domain_name_label: The domain name label. The concatenation of the domain name label and
the regionalized DNS zone make up the fully qualified domain name associated with the public IP
address. If a domain name label is specified, an A DNS record is created for the public IP in
the Microsoft Azure DNS system.
:type domain_name_label: str
:param fqdn: The Fully Qualified Domain Name of the A DNS record associated with the public IP.
This is the concatenation of the domainNameLabel and the regionalized DNS zone.
:type fqdn: str
:param reverse_fqdn: The reverse FQDN. A user-visible, fully qualified domain name that
resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is
created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN.
:type reverse_fqdn: str
"""
_attribute_map = {
'domain_name_label': {'key': 'domainNameLabel', 'type': 'str'},
'fqdn': {'key': 'fqdn', 'type': 'str'},
'reverse_fqdn': {'key': 'reverseFqdn', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressDnsSettings, self).__init__(**kwargs)
self.domain_name_label = kwargs.get('domain_name_label', None)
self.fqdn = kwargs.get('fqdn', None)
self.reverse_fqdn = kwargs.get('reverse_fqdn', None)
class PublicIPAddressListResult(msrest.serialization.Model):
"""Response for ListPublicIpAddresses API service call.
:param value: A list of public IP addresses that exists in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PublicIPAddress]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PublicIPAddress]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PublicIPAddressSku(msrest.serialization.Model):
"""SKU of a public IP address.
:param name: Name of a public IP address SKU. Possible values include: "Basic", "Standard".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.PublicIPAddressSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class PublicIPPrefix(Resource):
"""Public IP prefix resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The public IP prefix SKU.
:type sku: ~azure.mgmt.network.v2020_04_01.models.PublicIPPrefixSku
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:param public_ip_address_version: The public IP address version. Possible values include:
"IPv4", "IPv6".
:type public_ip_address_version: str or ~azure.mgmt.network.v2020_04_01.models.IPVersion
:param ip_tags: The list of tags associated with the public IP prefix.
:type ip_tags: list[~azure.mgmt.network.v2020_04_01.models.IpTag]
:param prefix_length: The Length of the Public IP Prefix.
:type prefix_length: int
:ivar ip_prefix: The allocated Prefix.
:vartype ip_prefix: str
:ivar public_ip_addresses: The list of all referenced PublicIPAddresses.
:vartype public_ip_addresses:
list[~azure.mgmt.network.v2020_04_01.models.ReferencedPublicIpAddress]
:ivar load_balancer_frontend_ip_configuration: The reference to load balancer frontend IP
configuration associated with the public IP prefix.
:vartype load_balancer_frontend_ip_configuration:
~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar resource_guid: The resource GUID property of the public IP prefix resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the public IP prefix resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'ip_prefix': {'readonly': True},
'public_ip_addresses': {'readonly': True},
'load_balancer_frontend_ip_configuration': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'PublicIPPrefixSku'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'},
'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'},
'prefix_length': {'key': 'properties.prefixLength', 'type': 'int'},
'ip_prefix': {'key': 'properties.ipPrefix', 'type': 'str'},
'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[ReferencedPublicIpAddress]'},
'load_balancer_frontend_ip_configuration': {'key': 'properties.loadBalancerFrontendIpConfiguration', 'type': 'SubResource'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefix, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = None
self.zones = kwargs.get('zones', None)
self.public_ip_address_version = kwargs.get('public_ip_address_version', None)
self.ip_tags = kwargs.get('ip_tags', None)
self.prefix_length = kwargs.get('prefix_length', None)
self.ip_prefix = None
self.public_ip_addresses = None
self.load_balancer_frontend_ip_configuration = None
self.resource_guid = None
self.provisioning_state = None
class PublicIPPrefixListResult(msrest.serialization.Model):
"""Response for ListPublicIpPrefixes API service call.
:param value: A list of public IP prefixes that exists in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.PublicIPPrefix]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PublicIPPrefix]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefixListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PublicIPPrefixSku(msrest.serialization.Model):
"""SKU of a public IP prefix.
:param name: Name of a public IP prefix SKU. Possible values include: "Standard".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.PublicIPPrefixSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefixSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class QueryTroubleshootingParameters(msrest.serialization.Model):
"""Parameters that define the resource to query the troubleshooting result.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource ID to query the troubleshooting
result.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(QueryTroubleshootingParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class RadiusServer(msrest.serialization.Model):
"""Radius Server Settings.
All required parameters must be populated in order to send to Azure.
:param radius_server_address: Required. The address of this radius server.
:type radius_server_address: str
:param radius_server_score: The initial score assigned to this radius server.
:type radius_server_score: long
:param radius_server_secret: The secret used for this radius server.
:type radius_server_secret: str
"""
_validation = {
'radius_server_address': {'required': True},
}
_attribute_map = {
'radius_server_address': {'key': 'radiusServerAddress', 'type': 'str'},
'radius_server_score': {'key': 'radiusServerScore', 'type': 'long'},
'radius_server_secret': {'key': 'radiusServerSecret', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RadiusServer, self).__init__(**kwargs)
self.radius_server_address = kwargs['radius_server_address']
self.radius_server_score = kwargs.get('radius_server_score', None)
self.radius_server_secret = kwargs.get('radius_server_secret', None)
class RecordSet(msrest.serialization.Model):
"""A collective group of information about the record set information.
Variables are only populated by the server, and will be ignored when sending a request.
:param record_type: Resource record type.
:type record_type: str
:param record_set_name: Recordset name.
:type record_set_name: str
:param fqdn: Fqdn that resolves to private endpoint ip address.
:type fqdn: str
:ivar provisioning_state: The provisioning state of the recordset. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param ttl: Recordset time to live.
:type ttl: int
:param ip_addresses: The private ip address of the private endpoint.
:type ip_addresses: list[str]
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'record_type': {'key': 'recordType', 'type': 'str'},
'record_set_name': {'key': 'recordSetName', 'type': 'str'},
'fqdn': {'key': 'fqdn', 'type': 'str'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'ttl': {'key': 'ttl', 'type': 'int'},
'ip_addresses': {'key': 'ipAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(RecordSet, self).__init__(**kwargs)
self.record_type = kwargs.get('record_type', None)
self.record_set_name = kwargs.get('record_set_name', None)
self.fqdn = kwargs.get('fqdn', None)
self.provisioning_state = None
self.ttl = kwargs.get('ttl', None)
self.ip_addresses = kwargs.get('ip_addresses', None)
class ReferencedPublicIpAddress(msrest.serialization.Model):
"""Reference to a public IP address.
:param id: The PublicIPAddress Reference.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ReferencedPublicIpAddress, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ResourceNavigationLink(SubResource):
"""ResourceNavigationLink resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param linked_resource_type: Resource type of the linked resource.
:type linked_resource_type: str
:param link: Link to the external resource.
:type link: str
:ivar provisioning_state: The provisioning state of the resource navigation link resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'},
'link': {'key': 'properties.link', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceNavigationLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.linked_resource_type = kwargs.get('linked_resource_type', None)
self.link = kwargs.get('link', None)
self.provisioning_state = None
class ResourceNavigationLinksListResult(msrest.serialization.Model):
"""Response for ResourceNavigationLinks_List operation.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The resource navigation links in a subnet.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ResourceNavigationLink]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ResourceNavigationLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceNavigationLinksListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class RetentionPolicyParameters(msrest.serialization.Model):
"""Parameters that define the retention policy for flow log.
:param days: Number of days to retain flow log records.
:type days: int
:param enabled: Flag to enable/disable retention.
:type enabled: bool
"""
_attribute_map = {
'days': {'key': 'days', 'type': 'int'},
'enabled': {'key': 'enabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(RetentionPolicyParameters, self).__init__(**kwargs)
self.days = kwargs.get('days', 0)
self.enabled = kwargs.get('enabled', False)
class Route(SubResource):
"""Route resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param address_prefix: The destination CIDR to which the route applies.
:type address_prefix: str
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values
include: "VirtualNetworkGateway", "VnetLocal", "Internet", "VirtualAppliance", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2020_04_01.models.RouteNextHopType
:param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are
only allowed in routes where the next hop type is VirtualAppliance.
:type next_hop_ip_address: str
:ivar provisioning_state: The provisioning state of the route resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'next_hop_type': {'key': 'properties.nextHopType', 'type': 'str'},
'next_hop_ip_address': {'key': 'properties.nextHopIpAddress', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Route, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.address_prefix = kwargs.get('address_prefix', None)
self.next_hop_type = kwargs.get('next_hop_type', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.provisioning_state = None
class RouteFilter(Resource):
"""Route Filter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rules: Collection of RouteFilterRules contained within a route filter.
:type rules: list[~azure.mgmt.network.v2020_04_01.models.RouteFilterRule]
:ivar peerings: A collection of references to express route circuit peerings.
:vartype peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:ivar ipv6_peerings: A collection of references to express route circuit ipv6 peerings.
:vartype ipv6_peerings: list[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the route filter resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'peerings': {'readonly': True},
'ipv6_peerings': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilter, self).__init__(**kwargs)
self.etag = None
self.rules = kwargs.get('rules', None)
self.peerings = None
self.ipv6_peerings = None
self.provisioning_state = None
class RouteFilterListResult(msrest.serialization.Model):
"""Response for the ListRouteFilters API service call.
:param value: A list of route filters in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.RouteFilter]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteFilter]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteFilterRule(SubResource):
"""Route Filter Rule Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param location: Resource location.
:type location: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param access: The access type of the rule. Possible values include: "Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2020_04_01.models.Access
:param route_filter_rule_type: The rule type of the rule. Possible values include: "Community".
:type route_filter_rule_type: str or ~azure.mgmt.network.v2020_04_01.models.RouteFilterRuleType
:param communities: The collection for bgp community values to filter on. e.g.
['12076:5010','12076:5020'].
:type communities: list[str]
:ivar provisioning_state: The provisioning state of the route filter rule resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'},
'communities': {'key': 'properties.communities', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.location = kwargs.get('location', None)
self.etag = None
self.access = kwargs.get('access', None)
self.route_filter_rule_type = kwargs.get('route_filter_rule_type', None)
self.communities = kwargs.get('communities', None)
self.provisioning_state = None
class RouteFilterRuleListResult(msrest.serialization.Model):
"""Response for the ListRouteFilterRules API service call.
:param value: A list of RouteFilterRules in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.RouteFilterRule]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteFilterRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteListResult(msrest.serialization.Model):
"""Response for the ListRoute API service call.
:param value: A list of routes in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.Route]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Route]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteTable(Resource):
"""Route table resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param routes: Collection of routes contained within a route table.
:type routes: list[~azure.mgmt.network.v2020_04_01.models.Route]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2020_04_01.models.Subnet]
:param disable_bgp_route_propagation: Whether to disable the routes learned by BGP on that
route table. True means disable.
:type disable_bgp_route_propagation: bool
:ivar provisioning_state: The provisioning state of the route table resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'subnets': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'routes': {'key': 'properties.routes', 'type': '[Route]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'disable_bgp_route_propagation': {'key': 'properties.disableBgpRoutePropagation', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteTable, self).__init__(**kwargs)
self.etag = None
self.routes = kwargs.get('routes', None)
self.subnets = None
self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None)
self.provisioning_state = None
class RouteTableListResult(msrest.serialization.Model):
"""Response for the ListRouteTable API service call.
:param value: A list of route tables in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.RouteTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RoutingConfiguration(msrest.serialization.Model):
"""Routing Configuration indicating the associated and propagated route tables for this connection.
:param associated_route_table: The resource id RouteTable associated with this
RoutingConfiguration.
:type associated_route_table: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param propagated_route_tables: The list of RouteTables to advertise the routes to.
:type propagated_route_tables: ~azure.mgmt.network.v2020_04_01.models.PropagatedRouteTable
:param vnet_routes: List of routes that control routing from VirtualHub into a virtual network
connection.
:type vnet_routes: ~azure.mgmt.network.v2020_04_01.models.VnetRoute
"""
_attribute_map = {
'associated_route_table': {'key': 'associatedRouteTable', 'type': 'SubResource'},
'propagated_route_tables': {'key': 'propagatedRouteTables', 'type': 'PropagatedRouteTable'},
'vnet_routes': {'key': 'vnetRoutes', 'type': 'VnetRoute'},
}
def __init__(
self,
**kwargs
):
super(RoutingConfiguration, self).__init__(**kwargs)
self.associated_route_table = kwargs.get('associated_route_table', None)
self.propagated_route_tables = kwargs.get('propagated_route_tables', None)
self.vnet_routes = kwargs.get('vnet_routes', None)
class SecurityGroupNetworkInterface(msrest.serialization.Model):
"""Network interface and all its associated security rules.
:param id: ID of the network interface.
:type id: str
:param security_rule_associations: All security rules associated with the network interface.
:type security_rule_associations:
~azure.mgmt.network.v2020_04_01.models.SecurityRuleAssociations
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rule_associations': {'key': 'securityRuleAssociations', 'type': 'SecurityRuleAssociations'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupNetworkInterface, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.security_rule_associations = kwargs.get('security_rule_associations', None)
class SecurityGroupViewParameters(msrest.serialization.Model):
"""Parameters that define the VM to check security groups for.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. ID of the target VM.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupViewParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class SecurityGroupViewResult(msrest.serialization.Model):
"""The information about security rules applied to the specified VM.
:param network_interfaces: List of network interfaces on the specified VM.
:type network_interfaces:
list[~azure.mgmt.network.v2020_04_01.models.SecurityGroupNetworkInterface]
"""
_attribute_map = {
'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetworkInterface]'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupViewResult, self).__init__(**kwargs)
self.network_interfaces = kwargs.get('network_interfaces', None)
class SecurityPartnerProvider(Resource):
"""Security Partner Provider resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the Security Partner Provider resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param security_provider_name: The security provider name. Possible values include: "ZScaler",
"IBoss", "Checkpoint".
:type security_provider_name: str or
~azure.mgmt.network.v2020_04_01.models.SecurityProviderName
:ivar connection_status: The connection status with the Security Partner Provider. Possible
values include: "Unknown", "PartiallyConnected", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2020_04_01.models.SecurityPartnerProviderConnectionStatus
:param virtual_hub: The virtualHub to which the Security Partner Provider belongs.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'connection_status': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(SecurityPartnerProvider, self).__init__(**kwargs)
self.etag = None
self.provisioning_state = None
self.security_provider_name = kwargs.get('security_provider_name', None)
self.connection_status = None
self.virtual_hub = kwargs.get('virtual_hub', None)
class SecurityPartnerProviderListResult(msrest.serialization.Model):
"""Response for ListSecurityPartnerProviders API service call.
:param value: List of Security Partner Providers in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.SecurityPartnerProvider]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[SecurityPartnerProvider]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityPartnerProviderListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class SecurityRule(SubResource):
"""Network security rule.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param description: A description for this rule. Restricted to 140 chars.
:type description: str
:param protocol: Network protocol this rule applies to. Possible values include: "Tcp", "Udp",
"Icmp", "Esp", "*", "Ah".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.SecurityRuleProtocol
:param source_port_range: The source port or range. Integer or range between 0 and 65535.
Asterisk '*' can also be used to match all ports.
:type source_port_range: str
:param destination_port_range: The destination port or range. Integer or range between 0 and
65535. Asterisk '*' can also be used to match all ports.
:type destination_port_range: str
:param source_address_prefix: The CIDR or source IP range. Asterisk '*' can also be used to
match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet'
can also be used. If this is an ingress rule, specifies where network traffic originates from.
:type source_address_prefix: str
:param source_address_prefixes: The CIDR or source IP ranges.
:type source_address_prefixes: list[str]
:param source_application_security_groups: The application security group specified as source.
:type source_application_security_groups:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationSecurityGroup]
:param destination_address_prefix: The destination address prefix. CIDR or destination IP
range. Asterisk '*' can also be used to match all source IPs. Default tags such as
'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
:type destination_address_prefix: str
:param destination_address_prefixes: The destination address prefixes. CIDR or destination IP
ranges.
:type destination_address_prefixes: list[str]
:param destination_application_security_groups: The application security group specified as
destination.
:type destination_application_security_groups:
list[~azure.mgmt.network.v2020_04_01.models.ApplicationSecurityGroup]
:param source_port_ranges: The source port ranges.
:type source_port_ranges: list[str]
:param destination_port_ranges: The destination port ranges.
:type destination_port_ranges: list[str]
:param access: The network traffic is allowed or denied. Possible values include: "Allow",
"Deny".
:type access: str or ~azure.mgmt.network.v2020_04_01.models.SecurityRuleAccess
:param priority: The priority of the rule. The value can be between 100 and 4096. The priority
number must be unique for each rule in the collection. The lower the priority number, the
higher the priority of the rule.
:type priority: int
:param direction: The direction of the rule. The direction specifies if rule will be evaluated
on incoming or outgoing traffic. Possible values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2020_04_01.models.SecurityRuleDirection
:ivar provisioning_state: The provisioning state of the security rule resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'source_port_range': {'key': 'properties.sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'properties.destinationPortRange', 'type': 'str'},
'source_address_prefix': {'key': 'properties.sourceAddressPrefix', 'type': 'str'},
'source_address_prefixes': {'key': 'properties.sourceAddressPrefixes', 'type': '[str]'},
'source_application_security_groups': {'key': 'properties.sourceApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'destination_address_prefix': {'key': 'properties.destinationAddressPrefix', 'type': 'str'},
'destination_address_prefixes': {'key': 'properties.destinationAddressPrefixes', 'type': '[str]'},
'destination_application_security_groups': {'key': 'properties.destinationApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'source_port_ranges': {'key': 'properties.sourcePortRanges', 'type': '[str]'},
'destination_port_ranges': {'key': 'properties.destinationPortRanges', 'type': '[str]'},
'access': {'key': 'properties.access', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'direction': {'key': 'properties.direction', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.description = kwargs.get('description', None)
self.protocol = kwargs.get('protocol', None)
self.source_port_range = kwargs.get('source_port_range', None)
self.destination_port_range = kwargs.get('destination_port_range', None)
self.source_address_prefix = kwargs.get('source_address_prefix', None)
self.source_address_prefixes = kwargs.get('source_address_prefixes', None)
self.source_application_security_groups = kwargs.get('source_application_security_groups', None)
self.destination_address_prefix = kwargs.get('destination_address_prefix', None)
self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None)
self.destination_application_security_groups = kwargs.get('destination_application_security_groups', None)
self.source_port_ranges = kwargs.get('source_port_ranges', None)
self.destination_port_ranges = kwargs.get('destination_port_ranges', None)
self.access = kwargs.get('access', None)
self.priority = kwargs.get('priority', None)
self.direction = kwargs.get('direction', None)
self.provisioning_state = None
class SecurityRuleAssociations(msrest.serialization.Model):
"""All security rules associated with the network interface.
:param network_interface_association: Network interface and it's custom security rules.
:type network_interface_association:
~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceAssociation
:param subnet_association: Subnet and it's custom security rules.
:type subnet_association: ~azure.mgmt.network.v2020_04_01.models.SubnetAssociation
:param default_security_rules: Collection of default security rules of the network security
group.
:type default_security_rules: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
:param effective_security_rules: Collection of effective security rules.
:type effective_security_rules:
list[~azure.mgmt.network.v2020_04_01.models.EffectiveNetworkSecurityRule]
"""
_attribute_map = {
'network_interface_association': {'key': 'networkInterfaceAssociation', 'type': 'NetworkInterfaceAssociation'},
'subnet_association': {'key': 'subnetAssociation', 'type': 'SubnetAssociation'},
'default_security_rules': {'key': 'defaultSecurityRules', 'type': '[SecurityRule]'},
'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(SecurityRuleAssociations, self).__init__(**kwargs)
self.network_interface_association = kwargs.get('network_interface_association', None)
self.subnet_association = kwargs.get('subnet_association', None)
self.default_security_rules = kwargs.get('default_security_rules', None)
self.effective_security_rules = kwargs.get('effective_security_rules', None)
class SecurityRuleListResult(msrest.serialization.Model):
"""Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a network security group.
:param value: The security rules in a network security group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[SecurityRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ServiceAssociationLink(SubResource):
"""ServiceAssociationLink resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param linked_resource_type: Resource type of the linked resource.
:type linked_resource_type: str
:param link: Link to the external resource.
:type link: str
:ivar provisioning_state: The provisioning state of the service association link resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param allow_delete: If true, the resource can be deleted.
:type allow_delete: bool
:param locations: A list of locations.
:type locations: list[str]
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'},
'link': {'key': 'properties.link', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'allow_delete': {'key': 'properties.allowDelete', 'type': 'bool'},
'locations': {'key': 'properties.locations', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ServiceAssociationLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.linked_resource_type = kwargs.get('linked_resource_type', None)
self.link = kwargs.get('link', None)
self.provisioning_state = None
self.allow_delete = kwargs.get('allow_delete', None)
self.locations = kwargs.get('locations', None)
class ServiceAssociationLinksListResult(msrest.serialization.Model):
"""Response for ServiceAssociationLinks_List operation.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The service association links in a subnet.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ServiceAssociationLink]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceAssociationLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceAssociationLinksListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ServiceEndpointPolicy(Resource):
"""Service End point policy resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param service_endpoint_policy_definitions: A collection of service endpoint policy definitions
of the service endpoint policy.
:type service_endpoint_policy_definitions:
list[~azure.mgmt.network.v2020_04_01.models.ServiceEndpointPolicyDefinition]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2020_04_01.models.Subnet]
:ivar resource_guid: The resource GUID property of the service endpoint policy resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the service endpoint policy resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'subnets': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'service_endpoint_policy_definitions': {'key': 'properties.serviceEndpointPolicyDefinitions', 'type': '[ServiceEndpointPolicyDefinition]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicy, self).__init__(**kwargs)
self.etag = None
self.service_endpoint_policy_definitions = kwargs.get('service_endpoint_policy_definitions', None)
self.subnets = None
self.resource_guid = None
self.provisioning_state = None
class ServiceEndpointPolicyDefinition(SubResource):
"""Service Endpoint policy definitions.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param description: A description for this rule. Restricted to 140 chars.
:type description: str
:param service: Service endpoint name.
:type service: str
:param service_resources: A list of service resources.
:type service_resources: list[str]
:ivar provisioning_state: The provisioning state of the service endpoint policy definition
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'service': {'key': 'properties.service', 'type': 'str'},
'service_resources': {'key': 'properties.serviceResources', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyDefinition, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.description = kwargs.get('description', None)
self.service = kwargs.get('service', None)
self.service_resources = kwargs.get('service_resources', None)
self.provisioning_state = None
class ServiceEndpointPolicyDefinitionListResult(msrest.serialization.Model):
"""Response for ListServiceEndpointPolicyDefinition API service call. Retrieves all service endpoint policy definition that belongs to a service endpoint policy.
:param value: The service endpoint policy definition in a service endpoint policy.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ServiceEndpointPolicyDefinition]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceEndpointPolicyDefinition]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyDefinitionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ServiceEndpointPolicyListResult(msrest.serialization.Model):
"""Response for ListServiceEndpointPolicies API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ServiceEndpointPolicy resources.
:type value: list[~azure.mgmt.network.v2020_04_01.models.ServiceEndpointPolicy]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceEndpointPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ServiceEndpointPropertiesFormat(msrest.serialization.Model):
"""The service endpoint properties.
Variables are only populated by the server, and will be ignored when sending a request.
:param service: The type of the endpoint service.
:type service: str
:param locations: A list of locations.
:type locations: list[str]
:ivar provisioning_state: The provisioning state of the service endpoint resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'service': {'key': 'service', 'type': 'str'},
'locations': {'key': 'locations', 'type': '[str]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPropertiesFormat, self).__init__(**kwargs)
self.service = kwargs.get('service', None)
self.locations = kwargs.get('locations', None)
self.provisioning_state = None
class ServiceTagInformation(msrest.serialization.Model):
"""The service tag information.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar properties: Properties of the service tag information.
:vartype properties:
~azure.mgmt.network.v2020_04_01.models.ServiceTagInformationPropertiesFormat
:ivar name: The name of service tag.
:vartype name: str
:ivar id: The ID of service tag.
:vartype id: str
"""
_validation = {
'properties': {'readonly': True},
'name': {'readonly': True},
'id': {'readonly': True},
}
_attribute_map = {
'properties': {'key': 'properties', 'type': 'ServiceTagInformationPropertiesFormat'},
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagInformation, self).__init__(**kwargs)
self.properties = None
self.name = None
self.id = None
class ServiceTagInformationPropertiesFormat(msrest.serialization.Model):
"""Properties of the service tag information.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar change_number: The iteration number of service tag.
:vartype change_number: str
:ivar region: The region of service tag.
:vartype region: str
:ivar system_service: The name of system service.
:vartype system_service: str
:ivar address_prefixes: The list of IP address prefixes.
:vartype address_prefixes: list[str]
"""
_validation = {
'change_number': {'readonly': True},
'region': {'readonly': True},
'system_service': {'readonly': True},
'address_prefixes': {'readonly': True},
}
_attribute_map = {
'change_number': {'key': 'changeNumber', 'type': 'str'},
'region': {'key': 'region', 'type': 'str'},
'system_service': {'key': 'systemService', 'type': 'str'},
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagInformationPropertiesFormat, self).__init__(**kwargs)
self.change_number = None
self.region = None
self.system_service = None
self.address_prefixes = None
class ServiceTagsListResult(msrest.serialization.Model):
"""Response for the ListServiceTags API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the cloud.
:vartype name: str
:ivar id: The ID of the cloud.
:vartype id: str
:ivar type: The azure resource type.
:vartype type: str
:ivar change_number: The iteration number.
:vartype change_number: str
:ivar cloud: The name of the cloud.
:vartype cloud: str
:ivar values: The list of service tag information resources.
:vartype values: list[~azure.mgmt.network.v2020_04_01.models.ServiceTagInformation]
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'type': {'readonly': True},
'change_number': {'readonly': True},
'cloud': {'readonly': True},
'values': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'change_number': {'key': 'changeNumber', 'type': 'str'},
'cloud': {'key': 'cloud', 'type': 'str'},
'values': {'key': 'values', 'type': '[ServiceTagInformation]'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagsListResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.type = None
self.change_number = None
self.cloud = None
self.values = None
class SessionIds(msrest.serialization.Model):
"""List of session IDs.
:param session_ids: List of session IDs.
:type session_ids: list[str]
"""
_attribute_map = {
'session_ids': {'key': 'sessionIds', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(SessionIds, self).__init__(**kwargs)
self.session_ids = kwargs.get('session_ids', None)
class StaticRoute(msrest.serialization.Model):
"""List of all Static Routes.
:param name: The name of the StaticRoute that is unique within a VnetRoute.
:type name: str
:param address_prefixes: List of all address prefixes.
:type address_prefixes: list[str]
:param next_hop_ip_address: The ip address of the next hop.
:type next_hop_ip_address: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(StaticRoute, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.address_prefixes = kwargs.get('address_prefixes', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
class Subnet(SubResource):
"""Subnet in a virtual network resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param address_prefix: The address prefix for the subnet.
:type address_prefix: str
:param address_prefixes: List of address prefixes for the subnet.
:type address_prefixes: list[str]
:param network_security_group: The reference to the NetworkSecurityGroup resource.
:type network_security_group: ~azure.mgmt.network.v2020_04_01.models.NetworkSecurityGroup
:param route_table: The reference to the RouteTable resource.
:type route_table: ~azure.mgmt.network.v2020_04_01.models.RouteTable
:param nat_gateway: Nat gateway associated with this subnet.
:type nat_gateway: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param service_endpoints: An array of service endpoints.
:type service_endpoints:
list[~azure.mgmt.network.v2020_04_01.models.ServiceEndpointPropertiesFormat]
:param service_endpoint_policies: An array of service endpoint policies.
:type service_endpoint_policies:
list[~azure.mgmt.network.v2020_04_01.models.ServiceEndpointPolicy]
:ivar private_endpoints: An array of references to private endpoints.
:vartype private_endpoints: list[~azure.mgmt.network.v2020_04_01.models.PrivateEndpoint]
:ivar ip_configurations: An array of references to the network interface IP configurations
using subnet.
:vartype ip_configurations: list[~azure.mgmt.network.v2020_04_01.models.IPConfiguration]
:ivar ip_configuration_profiles: Array of IP configuration profiles which reference this
subnet.
:vartype ip_configuration_profiles:
list[~azure.mgmt.network.v2020_04_01.models.IPConfigurationProfile]
:param ip_allocations: Array of IpAllocation which reference this subnet.
:type ip_allocations: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar resource_navigation_links: An array of references to the external resources using subnet.
:vartype resource_navigation_links:
list[~azure.mgmt.network.v2020_04_01.models.ResourceNavigationLink]
:ivar service_association_links: An array of references to services injecting into this subnet.
:vartype service_association_links:
list[~azure.mgmt.network.v2020_04_01.models.ServiceAssociationLink]
:param delegations: An array of references to the delegations on the subnet.
:type delegations: list[~azure.mgmt.network.v2020_04_01.models.Delegation]
:ivar purpose: A read-only string identifying the intention of use for this subnet based on
delegations and other user-defined properties.
:vartype purpose: str
:ivar provisioning_state: The provisioning state of the subnet resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param private_endpoint_network_policies: Enable or Disable apply network policies on private
end point in the subnet.
:type private_endpoint_network_policies: str
:param private_link_service_network_policies: Enable or Disable apply network policies on
private link service in the subnet.
:type private_link_service_network_policies: str
"""
_validation = {
'etag': {'readonly': True},
'private_endpoints': {'readonly': True},
'ip_configurations': {'readonly': True},
'ip_configuration_profiles': {'readonly': True},
'resource_navigation_links': {'readonly': True},
'service_association_links': {'readonly': True},
'purpose': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'address_prefixes': {'key': 'properties.addressPrefixes', 'type': '[str]'},
'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'},
'route_table': {'key': 'properties.routeTable', 'type': 'RouteTable'},
'nat_gateway': {'key': 'properties.natGateway', 'type': 'SubResource'},
'service_endpoints': {'key': 'properties.serviceEndpoints', 'type': '[ServiceEndpointPropertiesFormat]'},
'service_endpoint_policies': {'key': 'properties.serviceEndpointPolicies', 'type': '[ServiceEndpointPolicy]'},
'private_endpoints': {'key': 'properties.privateEndpoints', 'type': '[PrivateEndpoint]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfiguration]'},
'ip_configuration_profiles': {'key': 'properties.ipConfigurationProfiles', 'type': '[IPConfigurationProfile]'},
'ip_allocations': {'key': 'properties.ipAllocations', 'type': '[SubResource]'},
'resource_navigation_links': {'key': 'properties.resourceNavigationLinks', 'type': '[ResourceNavigationLink]'},
'service_association_links': {'key': 'properties.serviceAssociationLinks', 'type': '[ServiceAssociationLink]'},
'delegations': {'key': 'properties.delegations', 'type': '[Delegation]'},
'purpose': {'key': 'properties.purpose', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_endpoint_network_policies': {'key': 'properties.privateEndpointNetworkPolicies', 'type': 'str'},
'private_link_service_network_policies': {'key': 'properties.privateLinkServiceNetworkPolicies', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Subnet, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.address_prefix = kwargs.get('address_prefix', None)
self.address_prefixes = kwargs.get('address_prefixes', None)
self.network_security_group = kwargs.get('network_security_group', None)
self.route_table = kwargs.get('route_table', None)
self.nat_gateway = kwargs.get('nat_gateway', None)
self.service_endpoints = kwargs.get('service_endpoints', None)
self.service_endpoint_policies = kwargs.get('service_endpoint_policies', None)
self.private_endpoints = None
self.ip_configurations = None
self.ip_configuration_profiles = None
self.ip_allocations = kwargs.get('ip_allocations', None)
self.resource_navigation_links = None
self.service_association_links = None
self.delegations = kwargs.get('delegations', None)
self.purpose = None
self.provisioning_state = None
self.private_endpoint_network_policies = kwargs.get('private_endpoint_network_policies', None)
self.private_link_service_network_policies = kwargs.get('private_link_service_network_policies', None)
class SubnetAssociation(msrest.serialization.Model):
"""Subnet and it's custom security rules.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Subnet ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules: list[~azure.mgmt.network.v2020_04_01.models.SecurityRule]
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(SubnetAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
class SubnetListResult(msrest.serialization.Model):
"""Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network.
:param value: The subnets in a virtual network.
:type value: list[~azure.mgmt.network.v2020_04_01.models.Subnet]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Subnet]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubnetListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class TagsObject(msrest.serialization.Model):
"""Tags object for patch operations.
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(TagsObject, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
class Topology(msrest.serialization.Model):
"""Topology of the specified resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: GUID representing the operation id.
:vartype id: str
:ivar created_date_time: The datetime when the topology was initially created for the resource
group.
:vartype created_date_time: ~datetime.datetime
:ivar last_modified: The datetime when the topology was last modified.
:vartype last_modified: ~datetime.datetime
:param resources: A list of topology resources.
:type resources: list[~azure.mgmt.network.v2020_04_01.models.TopologyResource]
"""
_validation = {
'id': {'readonly': True},
'created_date_time': {'readonly': True},
'last_modified': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'created_date_time': {'key': 'createdDateTime', 'type': 'iso-8601'},
'last_modified': {'key': 'lastModified', 'type': 'iso-8601'},
'resources': {'key': 'resources', 'type': '[TopologyResource]'},
}
def __init__(
self,
**kwargs
):
super(Topology, self).__init__(**kwargs)
self.id = None
self.created_date_time = None
self.last_modified = None
self.resources = kwargs.get('resources', None)
class TopologyAssociation(msrest.serialization.Model):
"""Resources that have an association with the parent resource.
:param name: The name of the resource that is associated with the parent resource.
:type name: str
:param resource_id: The ID of the resource that is associated with the parent resource.
:type resource_id: str
:param association_type: The association type of the child resource to the parent resource.
Possible values include: "Associated", "Contains".
:type association_type: str or ~azure.mgmt.network.v2020_04_01.models.AssociationType
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'association_type': {'key': 'associationType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TopologyAssociation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.resource_id = kwargs.get('resource_id', None)
self.association_type = kwargs.get('association_type', None)
class TopologyParameters(msrest.serialization.Model):
"""Parameters that define the representation of topology.
:param target_resource_group_name: The name of the target resource group to perform topology
on.
:type target_resource_group_name: str
:param target_virtual_network: The reference to the Virtual Network resource.
:type target_virtual_network: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param target_subnet: The reference to the Subnet resource.
:type target_subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
"""
_attribute_map = {
'target_resource_group_name': {'key': 'targetResourceGroupName', 'type': 'str'},
'target_virtual_network': {'key': 'targetVirtualNetwork', 'type': 'SubResource'},
'target_subnet': {'key': 'targetSubnet', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(TopologyParameters, self).__init__(**kwargs)
self.target_resource_group_name = kwargs.get('target_resource_group_name', None)
self.target_virtual_network = kwargs.get('target_virtual_network', None)
self.target_subnet = kwargs.get('target_subnet', None)
class TopologyResource(msrest.serialization.Model):
"""The network resource topology information for the given resource group.
:param name: Name of the resource.
:type name: str
:param id: ID of the resource.
:type id: str
:param location: Resource location.
:type location: str
:param associations: Holds the associations the resource has with other resources in the
resource group.
:type associations: list[~azure.mgmt.network.v2020_04_01.models.TopologyAssociation]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'associations': {'key': 'associations', 'type': '[TopologyAssociation]'},
}
def __init__(
self,
**kwargs
):
super(TopologyResource, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.location = kwargs.get('location', None)
self.associations = kwargs.get('associations', None)
class TrafficAnalyticsConfigurationProperties(msrest.serialization.Model):
"""Parameters that define the configuration of traffic analytics.
:param enabled: Flag to enable/disable traffic analytics.
:type enabled: bool
:param workspace_id: The resource guid of the attached workspace.
:type workspace_id: str
:param workspace_region: The location of the attached workspace.
:type workspace_region: str
:param workspace_resource_id: Resource Id of the attached workspace.
:type workspace_resource_id: str
:param traffic_analytics_interval: The interval in minutes which would decide how frequently TA
service should do flow analytics.
:type traffic_analytics_interval: int
"""
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'workspace_id': {'key': 'workspaceId', 'type': 'str'},
'workspace_region': {'key': 'workspaceRegion', 'type': 'str'},
'workspace_resource_id': {'key': 'workspaceResourceId', 'type': 'str'},
'traffic_analytics_interval': {'key': 'trafficAnalyticsInterval', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(TrafficAnalyticsConfigurationProperties, self).__init__(**kwargs)
self.enabled = kwargs.get('enabled', None)
self.workspace_id = kwargs.get('workspace_id', None)
self.workspace_region = kwargs.get('workspace_region', None)
self.workspace_resource_id = kwargs.get('workspace_resource_id', None)
self.traffic_analytics_interval = kwargs.get('traffic_analytics_interval', None)
class TrafficAnalyticsProperties(msrest.serialization.Model):
"""Parameters that define the configuration of traffic analytics.
:param network_watcher_flow_analytics_configuration: Parameters that define the configuration
of traffic analytics.
:type network_watcher_flow_analytics_configuration:
~azure.mgmt.network.v2020_04_01.models.TrafficAnalyticsConfigurationProperties
"""
_attribute_map = {
'network_watcher_flow_analytics_configuration': {'key': 'networkWatcherFlowAnalyticsConfiguration', 'type': 'TrafficAnalyticsConfigurationProperties'},
}
def __init__(
self,
**kwargs
):
super(TrafficAnalyticsProperties, self).__init__(**kwargs)
self.network_watcher_flow_analytics_configuration = kwargs.get('network_watcher_flow_analytics_configuration', None)
class TrafficSelectorPolicy(msrest.serialization.Model):
"""An traffic selector policy for a virtual network gateway connection.
All required parameters must be populated in order to send to Azure.
:param local_address_ranges: Required. A collection of local address spaces in CIDR format.
:type local_address_ranges: list[str]
:param remote_address_ranges: Required. A collection of remote address spaces in CIDR format.
:type remote_address_ranges: list[str]
"""
_validation = {
'local_address_ranges': {'required': True},
'remote_address_ranges': {'required': True},
}
_attribute_map = {
'local_address_ranges': {'key': 'localAddressRanges', 'type': '[str]'},
'remote_address_ranges': {'key': 'remoteAddressRanges', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(TrafficSelectorPolicy, self).__init__(**kwargs)
self.local_address_ranges = kwargs['local_address_ranges']
self.remote_address_ranges = kwargs['remote_address_ranges']
class TroubleshootingDetails(msrest.serialization.Model):
"""Information gained from troubleshooting of specified resource.
:param id: The id of the get troubleshoot operation.
:type id: str
:param reason_type: Reason type of failure.
:type reason_type: str
:param summary: A summary of troubleshooting.
:type summary: str
:param detail: Details on troubleshooting results.
:type detail: str
:param recommended_actions: List of recommended actions.
:type recommended_actions:
list[~azure.mgmt.network.v2020_04_01.models.TroubleshootingRecommendedActions]
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'reason_type': {'key': 'reasonType', 'type': 'str'},
'summary': {'key': 'summary', 'type': 'str'},
'detail': {'key': 'detail', 'type': 'str'},
'recommended_actions': {'key': 'recommendedActions', 'type': '[TroubleshootingRecommendedActions]'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingDetails, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.reason_type = kwargs.get('reason_type', None)
self.summary = kwargs.get('summary', None)
self.detail = kwargs.get('detail', None)
self.recommended_actions = kwargs.get('recommended_actions', None)
class TroubleshootingParameters(msrest.serialization.Model):
"""Parameters that define the resource to troubleshoot.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource to troubleshoot.
:type target_resource_id: str
:param storage_id: Required. The ID for the storage account to save the troubleshoot result.
:type storage_id: str
:param storage_path: Required. The path to the blob to save the troubleshoot result in.
:type storage_path: str
"""
_validation = {
'target_resource_id': {'required': True},
'storage_id': {'required': True},
'storage_path': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'storage_id': {'key': 'properties.storageId', 'type': 'str'},
'storage_path': {'key': 'properties.storagePath', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.storage_id = kwargs['storage_id']
self.storage_path = kwargs['storage_path']
class TroubleshootingRecommendedActions(msrest.serialization.Model):
"""Recommended actions based on discovered issues.
:param action_id: ID of the recommended action.
:type action_id: str
:param action_text: Description of recommended actions.
:type action_text: str
:param action_uri: The uri linking to a documentation for the recommended troubleshooting
actions.
:type action_uri: str
:param action_uri_text: The information from the URI for the recommended troubleshooting
actions.
:type action_uri_text: str
"""
_attribute_map = {
'action_id': {'key': 'actionId', 'type': 'str'},
'action_text': {'key': 'actionText', 'type': 'str'},
'action_uri': {'key': 'actionUri', 'type': 'str'},
'action_uri_text': {'key': 'actionUriText', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingRecommendedActions, self).__init__(**kwargs)
self.action_id = kwargs.get('action_id', None)
self.action_text = kwargs.get('action_text', None)
self.action_uri = kwargs.get('action_uri', None)
self.action_uri_text = kwargs.get('action_uri_text', None)
class TroubleshootingResult(msrest.serialization.Model):
"""Troubleshooting information gained from specified resource.
:param start_time: The start time of the troubleshooting.
:type start_time: ~datetime.datetime
:param end_time: The end time of the troubleshooting.
:type end_time: ~datetime.datetime
:param code: The result code of the troubleshooting.
:type code: str
:param results: Information from troubleshooting.
:type results: list[~azure.mgmt.network.v2020_04_01.models.TroubleshootingDetails]
"""
_attribute_map = {
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'code': {'key': 'code', 'type': 'str'},
'results': {'key': 'results', 'type': '[TroubleshootingDetails]'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingResult, self).__init__(**kwargs)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
self.code = kwargs.get('code', None)
self.results = kwargs.get('results', None)
class TunnelConnectionHealth(msrest.serialization.Model):
"""VirtualNetworkGatewayConnection properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar tunnel: Tunnel name.
:vartype tunnel: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar ingress_bytes_transferred: The Ingress Bytes Transferred in this connection.
:vartype ingress_bytes_transferred: long
:ivar egress_bytes_transferred: The Egress Bytes Transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar last_connection_established_utc_time: The time at which connection was established in Utc
format.
:vartype last_connection_established_utc_time: str
"""
_validation = {
'tunnel': {'readonly': True},
'connection_status': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'last_connection_established_utc_time': {'readonly': True},
}
_attribute_map = {
'tunnel': {'key': 'tunnel', 'type': 'str'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'},
'last_connection_established_utc_time': {'key': 'lastConnectionEstablishedUtcTime', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TunnelConnectionHealth, self).__init__(**kwargs)
self.tunnel = None
self.connection_status = None
self.ingress_bytes_transferred = None
self.egress_bytes_transferred = None
self.last_connection_established_utc_time = None
class UnprepareNetworkPoliciesRequest(msrest.serialization.Model):
"""Details of UnprepareNetworkPolicies for Subnet.
:param service_name: The name of the service for which subnet is being unprepared for.
:type service_name: str
"""
_attribute_map = {
'service_name': {'key': 'serviceName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(UnprepareNetworkPoliciesRequest, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
class Usage(msrest.serialization.Model):
"""The network resource usage.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Resource identifier.
:vartype id: str
:param unit: Required. An enum describing the unit of measurement. Possible values include:
"Count".
:type unit: str or ~azure.mgmt.network.v2020_04_01.models.UsageUnit
:param current_value: Required. The current value of the usage.
:type current_value: long
:param limit: Required. The limit of usage.
:type limit: long
:param name: Required. The name of the type of usage.
:type name: ~azure.mgmt.network.v2020_04_01.models.UsageName
"""
_validation = {
'id': {'readonly': True},
'unit': {'required': True},
'current_value': {'required': True},
'limit': {'required': True},
'name': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'unit': {'key': 'unit', 'type': 'str'},
'current_value': {'key': 'currentValue', 'type': 'long'},
'limit': {'key': 'limit', 'type': 'long'},
'name': {'key': 'name', 'type': 'UsageName'},
}
def __init__(
self,
**kwargs
):
super(Usage, self).__init__(**kwargs)
self.id = None
self.unit = kwargs['unit']
self.current_value = kwargs['current_value']
self.limit = kwargs['limit']
self.name = kwargs['name']
class UsageName(msrest.serialization.Model):
"""The usage names.
:param value: A string describing the resource name.
:type value: str
:param localized_value: A localized string describing the resource name.
:type localized_value: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': 'str'},
'localized_value': {'key': 'localizedValue', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(UsageName, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.localized_value = kwargs.get('localized_value', None)
class UsagesListResult(msrest.serialization.Model):
"""The list usages operation response.
:param value: The list network resource usages.
:type value: list[~azure.mgmt.network.v2020_04_01.models.Usage]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Usage]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(UsagesListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VerificationIPFlowParameters(msrest.serialization.Model):
"""Parameters that define the IP flow to be verified.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the target resource to perform next-hop on.
:type target_resource_id: str
:param direction: Required. The direction of the packet represented as a 5-tuple. Possible
values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2020_04_01.models.Direction
:param protocol: Required. Protocol to be verified on. Possible values include: "TCP", "UDP".
:type protocol: str or ~azure.mgmt.network.v2020_04_01.models.IpFlowProtocol
:param local_port: Required. The local port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type local_port: str
:param remote_port: Required. The remote port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type remote_port: str
:param local_ip_address: Required. The local IP address. Acceptable values are valid IPv4
addresses.
:type local_ip_address: str
:param remote_ip_address: Required. The remote IP address. Acceptable values are valid IPv4
addresses.
:type remote_ip_address: str
:param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is
enabled on any of them, then this parameter must be specified. Otherwise optional).
:type target_nic_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
'direction': {'required': True},
'protocol': {'required': True},
'local_port': {'required': True},
'remote_port': {'required': True},
'local_ip_address': {'required': True},
'remote_ip_address': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'direction': {'key': 'direction', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'local_port': {'key': 'localPort', 'type': 'str'},
'remote_port': {'key': 'remotePort', 'type': 'str'},
'local_ip_address': {'key': 'localIPAddress', 'type': 'str'},
'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'},
'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VerificationIPFlowParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.direction = kwargs['direction']
self.protocol = kwargs['protocol']
self.local_port = kwargs['local_port']
self.remote_port = kwargs['remote_port']
self.local_ip_address = kwargs['local_ip_address']
self.remote_ip_address = kwargs['remote_ip_address']
self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None)
class VerificationIPFlowResult(msrest.serialization.Model):
"""Results of IP flow verification on the target resource.
:param access: Indicates whether the traffic is allowed or denied. Possible values include:
"Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2020_04_01.models.Access
:param rule_name: Name of the rule. If input is not matched against any security rule, it is
not displayed.
:type rule_name: str
"""
_attribute_map = {
'access': {'key': 'access', 'type': 'str'},
'rule_name': {'key': 'ruleName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VerificationIPFlowResult, self).__init__(**kwargs)
self.access = kwargs.get('access', None)
self.rule_name = kwargs.get('rule_name', None)
class VirtualApplianceNicProperties(msrest.serialization.Model):
"""Network Virtual Appliance NIC properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: NIC name.
:vartype name: str
:ivar public_ip_address: Public IP address.
:vartype public_ip_address: str
:ivar private_ip_address: Private IP address.
:vartype private_ip_address: str
"""
_validation = {
'name': {'readonly': True},
'public_ip_address': {'readonly': True},
'private_ip_address': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'public_ip_address': {'key': 'publicIpAddress', 'type': 'str'},
'private_ip_address': {'key': 'privateIpAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualApplianceNicProperties, self).__init__(**kwargs)
self.name = None
self.public_ip_address = None
self.private_ip_address = None
class VirtualApplianceSkuProperties(msrest.serialization.Model):
"""Network Virtual Appliance Sku Properties.
:param vendor: Virtual Appliance Vendor.
:type vendor: str
:param bundled_scale_unit: Virtual Appliance Scale Unit.
:type bundled_scale_unit: str
:param market_place_version: Virtual Appliance Version.
:type market_place_version: str
"""
_attribute_map = {
'vendor': {'key': 'vendor', 'type': 'str'},
'bundled_scale_unit': {'key': 'bundledScaleUnit', 'type': 'str'},
'market_place_version': {'key': 'marketPlaceVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualApplianceSkuProperties, self).__init__(**kwargs)
self.vendor = kwargs.get('vendor', None)
self.bundled_scale_unit = kwargs.get('bundled_scale_unit', None)
self.market_place_version = kwargs.get('market_place_version', None)
class VirtualHub(Resource):
"""VirtualHub Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_wan: The VirtualWAN to which the VirtualHub belongs.
:type virtual_wan: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param vpn_gateway: The VpnGateway associated with this VirtualHub.
:type vpn_gateway: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param p2_s_vpn_gateway: The P2SVpnGateway associated with this VirtualHub.
:type p2_s_vpn_gateway: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param express_route_gateway: The expressRouteGateway associated with this VirtualHub.
:type express_route_gateway: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param azure_firewall: The azureFirewall associated with this VirtualHub.
:type azure_firewall: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param security_partner_provider: The securityPartnerProvider associated with this VirtualHub.
:type security_partner_provider: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param virtual_network_connections: List of all vnet connections with this VirtualHub.
:type virtual_network_connections:
list[~azure.mgmt.network.v2020_04_01.models.HubVirtualNetworkConnection]
:param address_prefix: Address-prefix for this VirtualHub.
:type address_prefix: str
:param route_table: The routeTable associated with this virtual hub.
:type route_table: ~azure.mgmt.network.v2020_04_01.models.VirtualHubRouteTable
:ivar provisioning_state: The provisioning state of the virtual hub resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param security_provider_name: The Security Provider name.
:type security_provider_name: str
:param virtual_hub_route_table_v2_s: List of all virtual hub route table v2s associated with
this VirtualHub.
:type virtual_hub_route_table_v2_s:
list[~azure.mgmt.network.v2020_04_01.models.VirtualHubRouteTableV2]
:param sku: The sku of this VirtualHub.
:type sku: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'},
'vpn_gateway': {'key': 'properties.vpnGateway', 'type': 'SubResource'},
'p2_s_vpn_gateway': {'key': 'properties.p2SVpnGateway', 'type': 'SubResource'},
'express_route_gateway': {'key': 'properties.expressRouteGateway', 'type': 'SubResource'},
'azure_firewall': {'key': 'properties.azureFirewall', 'type': 'SubResource'},
'security_partner_provider': {'key': 'properties.securityPartnerProvider', 'type': 'SubResource'},
'virtual_network_connections': {'key': 'properties.virtualNetworkConnections', 'type': '[HubVirtualNetworkConnection]'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'route_table': {'key': 'properties.routeTable', 'type': 'VirtualHubRouteTable'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'},
'virtual_hub_route_table_v2_s': {'key': 'properties.virtualHubRouteTableV2s', 'type': '[VirtualHubRouteTableV2]'},
'sku': {'key': 'properties.sku', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHub, self).__init__(**kwargs)
self.etag = None
self.virtual_wan = kwargs.get('virtual_wan', None)
self.vpn_gateway = kwargs.get('vpn_gateway', None)
self.p2_s_vpn_gateway = kwargs.get('p2_s_vpn_gateway', None)
self.express_route_gateway = kwargs.get('express_route_gateway', None)
self.azure_firewall = kwargs.get('azure_firewall', None)
self.security_partner_provider = kwargs.get('security_partner_provider', None)
self.virtual_network_connections = kwargs.get('virtual_network_connections', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.route_table = kwargs.get('route_table', None)
self.provisioning_state = None
self.security_provider_name = kwargs.get('security_provider_name', None)
self.virtual_hub_route_table_v2_s = kwargs.get('virtual_hub_route_table_v2_s', None)
self.sku = kwargs.get('sku', None)
class VirtualHubId(msrest.serialization.Model):
"""Virtual Hub identifier.
:param id: The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be
deployed. The Virtual Hub resource and the ExpressRoute gateway resource reside in the same
subscription.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubId, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class VirtualHubRoute(msrest.serialization.Model):
"""VirtualHub route.
:param address_prefixes: List of all addressPrefixes.
:type address_prefixes: list[str]
:param next_hop_ip_address: NextHop ip address.
:type next_hop_ip_address: str
"""
_attribute_map = {
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRoute, self).__init__(**kwargs)
self.address_prefixes = kwargs.get('address_prefixes', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
class VirtualHubRouteTable(msrest.serialization.Model):
"""VirtualHub route table.
:param routes: List of all routes.
:type routes: list[~azure.mgmt.network.v2020_04_01.models.VirtualHubRoute]
"""
_attribute_map = {
'routes': {'key': 'routes', 'type': '[VirtualHubRoute]'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRouteTable, self).__init__(**kwargs)
self.routes = kwargs.get('routes', None)
class VirtualHubRouteTableV2(SubResource):
"""VirtualHubRouteTableV2 Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param routes: List of all routes.
:type routes: list[~azure.mgmt.network.v2020_04_01.models.VirtualHubRouteV2]
:param attached_connections: List of all connections attached to this route table v2.
:type attached_connections: list[str]
:ivar provisioning_state: The provisioning state of the virtual hub route table v2 resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'routes': {'key': 'properties.routes', 'type': '[VirtualHubRouteV2]'},
'attached_connections': {'key': 'properties.attachedConnections', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRouteTableV2, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.routes = kwargs.get('routes', None)
self.attached_connections = kwargs.get('attached_connections', None)
self.provisioning_state = None
class VirtualHubRouteV2(msrest.serialization.Model):
"""VirtualHubRouteTableV2 route.
:param destination_type: The type of destinations.
:type destination_type: str
:param destinations: List of all destinations.
:type destinations: list[str]
:param next_hop_type: The type of next hops.
:type next_hop_type: str
:param next_hops: NextHops ip address.
:type next_hops: list[str]
"""
_attribute_map = {
'destination_type': {'key': 'destinationType', 'type': 'str'},
'destinations': {'key': 'destinations', 'type': '[str]'},
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
'next_hops': {'key': 'nextHops', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRouteV2, self).__init__(**kwargs)
self.destination_type = kwargs.get('destination_type', None)
self.destinations = kwargs.get('destinations', None)
self.next_hop_type = kwargs.get('next_hop_type', None)
self.next_hops = kwargs.get('next_hops', None)
class VirtualNetwork(Resource):
"""Virtual Network resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param address_space: The AddressSpace that contains an array of IP address ranges that can be
used by subnets.
:type address_space: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param dhcp_options: The dhcpOptions that contains an array of DNS servers available to VMs
deployed in the virtual network.
:type dhcp_options: ~azure.mgmt.network.v2020_04_01.models.DhcpOptions
:param subnets: A list of subnets in a Virtual Network.
:type subnets: list[~azure.mgmt.network.v2020_04_01.models.Subnet]
:param virtual_network_peerings: A list of peerings in a Virtual Network.
:type virtual_network_peerings:
list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkPeering]
:ivar resource_guid: The resourceGuid property of the Virtual Network resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param enable_ddos_protection: Indicates if DDoS protection is enabled for all the protected
resources in the virtual network. It requires a DDoS protection plan associated with the
resource.
:type enable_ddos_protection: bool
:param enable_vm_protection: Indicates if VM protection is enabled for all the subnets in the
virtual network.
:type enable_vm_protection: bool
:param ddos_protection_plan: The DDoS protection plan associated with the virtual network.
:type ddos_protection_plan: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param bgp_communities: Bgp Communities sent over ExpressRoute with each route corresponding to
a prefix in this VNET.
:type bgp_communities: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkBgpCommunities
:param ip_allocations: Array of IpAllocation which reference this VNET.
:type ip_allocations: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'},
'dhcp_options': {'key': 'properties.dhcpOptions', 'type': 'DhcpOptions'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'virtual_network_peerings': {'key': 'properties.virtualNetworkPeerings', 'type': '[VirtualNetworkPeering]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'enable_ddos_protection': {'key': 'properties.enableDdosProtection', 'type': 'bool'},
'enable_vm_protection': {'key': 'properties.enableVmProtection', 'type': 'bool'},
'ddos_protection_plan': {'key': 'properties.ddosProtectionPlan', 'type': 'SubResource'},
'bgp_communities': {'key': 'properties.bgpCommunities', 'type': 'VirtualNetworkBgpCommunities'},
'ip_allocations': {'key': 'properties.ipAllocations', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetwork, self).__init__(**kwargs)
self.etag = None
self.address_space = kwargs.get('address_space', None)
self.dhcp_options = kwargs.get('dhcp_options', None)
self.subnets = kwargs.get('subnets', None)
self.virtual_network_peerings = kwargs.get('virtual_network_peerings', None)
self.resource_guid = None
self.provisioning_state = None
self.enable_ddos_protection = kwargs.get('enable_ddos_protection', False)
self.enable_vm_protection = kwargs.get('enable_vm_protection', False)
self.ddos_protection_plan = kwargs.get('ddos_protection_plan', None)
self.bgp_communities = kwargs.get('bgp_communities', None)
self.ip_allocations = kwargs.get('ip_allocations', None)
class VirtualNetworkBgpCommunities(msrest.serialization.Model):
"""Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param virtual_network_community: Required. The BGP community associated with the virtual
network.
:type virtual_network_community: str
:ivar regional_community: The BGP community associated with the region of the virtual network.
:vartype regional_community: str
"""
_validation = {
'virtual_network_community': {'required': True},
'regional_community': {'readonly': True},
}
_attribute_map = {
'virtual_network_community': {'key': 'virtualNetworkCommunity', 'type': 'str'},
'regional_community': {'key': 'regionalCommunity', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkBgpCommunities, self).__init__(**kwargs)
self.virtual_network_community = kwargs['virtual_network_community']
self.regional_community = None
class VirtualNetworkConnectionGatewayReference(msrest.serialization.Model):
"""A reference to VirtualNetworkGateway or LocalNetworkGateway resource.
All required parameters must be populated in order to send to Azure.
:param id: Required. The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
:type id: str
"""
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkConnectionGatewayReference, self).__init__(**kwargs)
self.id = kwargs['id']
class VirtualNetworkGateway(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param ip_configurations: IP configurations for virtual network gateway.
:type ip_configurations:
list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayIPConfiguration]
:param gateway_type: The type of this virtual network gateway. Possible values include: "Vpn",
"ExpressRoute".
:type gateway_type: str or ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayType
:param vpn_type: The type of this virtual network gateway. Possible values include:
"PolicyBased", "RouteBased".
:type vpn_type: str or ~azure.mgmt.network.v2020_04_01.models.VpnType
:param vpn_gateway_generation: The generation for this VirtualNetworkGateway. Must be None if
gatewayType is not VPN. Possible values include: "None", "Generation1", "Generation2".
:type vpn_gateway_generation: str or
~azure.mgmt.network.v2020_04_01.models.VpnGatewayGeneration
:param enable_bgp: Whether BGP is enabled for this virtual network gateway or not.
:type enable_bgp: bool
:param enable_private_ip_address: Whether private IP needs to be enabled on this gateway for
connections or not.
:type enable_private_ip_address: bool
:param active: ActiveActive flag.
:type active: bool
:param gateway_default_site: The reference to the LocalNetworkGateway resource which represents
local network site having default routes. Assign Null value in case of removing existing
default site setting.
:type gateway_default_site: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param sku: The reference to the VirtualNetworkGatewaySku resource which represents the SKU
selected for Virtual network gateway.
:type sku: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewaySku
:param vpn_client_configuration: The reference to the VpnClientConfiguration resource which
represents the P2S VpnClient configurations.
:type vpn_client_configuration: ~azure.mgmt.network.v2020_04_01.models.VpnClientConfiguration
:param bgp_settings: Virtual network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2020_04_01.models.BgpSettings
:param custom_routes: The reference to the address space resource which represents the custom
routes address space specified by the customer for virtual network gateway and VpnClient.
:type custom_routes: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:ivar resource_guid: The resource GUID property of the virtual network gateway resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network gateway resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param enable_dns_forwarding: Whether dns forwarding is enabled or not.
:type enable_dns_forwarding: bool
:ivar inbound_dns_forwarding_endpoint: The IP address allocated by the gateway to which dns
requests can be sent.
:vartype inbound_dns_forwarding_endpoint: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
'inbound_dns_forwarding_endpoint': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualNetworkGatewayIPConfiguration]'},
'gateway_type': {'key': 'properties.gatewayType', 'type': 'str'},
'vpn_type': {'key': 'properties.vpnType', 'type': 'str'},
'vpn_gateway_generation': {'key': 'properties.vpnGatewayGeneration', 'type': 'str'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'enable_private_ip_address': {'key': 'properties.enablePrivateIpAddress', 'type': 'bool'},
'active': {'key': 'properties.activeActive', 'type': 'bool'},
'gateway_default_site': {'key': 'properties.gatewayDefaultSite', 'type': 'SubResource'},
'sku': {'key': 'properties.sku', 'type': 'VirtualNetworkGatewaySku'},
'vpn_client_configuration': {'key': 'properties.vpnClientConfiguration', 'type': 'VpnClientConfiguration'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'custom_routes': {'key': 'properties.customRoutes', 'type': 'AddressSpace'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'enable_dns_forwarding': {'key': 'properties.enableDnsForwarding', 'type': 'bool'},
'inbound_dns_forwarding_endpoint': {'key': 'properties.inboundDnsForwardingEndpoint', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGateway, self).__init__(**kwargs)
self.etag = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.gateway_type = kwargs.get('gateway_type', None)
self.vpn_type = kwargs.get('vpn_type', None)
self.vpn_gateway_generation = kwargs.get('vpn_gateway_generation', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.enable_private_ip_address = kwargs.get('enable_private_ip_address', None)
self.active = kwargs.get('active', None)
self.gateway_default_site = kwargs.get('gateway_default_site', None)
self.sku = kwargs.get('sku', None)
self.vpn_client_configuration = kwargs.get('vpn_client_configuration', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.custom_routes = kwargs.get('custom_routes', None)
self.resource_guid = None
self.provisioning_state = None
self.enable_dns_forwarding = kwargs.get('enable_dns_forwarding', None)
self.inbound_dns_forwarding_endpoint = None
class VirtualNetworkGatewayConnection(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param authorization_key: The authorizationKey.
:type authorization_key: str
:param virtual_network_gateway1: Required. The reference to virtual network gateway resource.
:type virtual_network_gateway1: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGateway
:param virtual_network_gateway2: The reference to virtual network gateway resource.
:type virtual_network_gateway2: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGateway
:param local_network_gateway2: The reference to local network gateway resource.
:type local_network_gateway2: ~azure.mgmt.network.v2020_04_01.models.LocalNetworkGateway
:param connection_type: Required. Gateway connection type. Possible values include: "IPsec",
"Vnet2Vnet", "ExpressRoute", "VPNClient".
:type connection_type: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionType
:param connection_protocol: Connection protocol used for this connection. Possible values
include: "IKEv2", "IKEv1".
:type connection_protocol: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionProtocol
:param routing_weight: The routing weight.
:type routing_weight: int
:param dpd_timeout_seconds: The dead peer detection timeout of this connection in seconds.
:type dpd_timeout_seconds: int
:param shared_key: The IPSec shared key.
:type shared_key: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar tunnel_connection_status: Collection of all tunnels' connection health status.
:vartype tunnel_connection_status:
list[~azure.mgmt.network.v2020_04_01.models.TunnelConnectionHealth]
:ivar egress_bytes_transferred: The egress bytes transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes transferred in this connection.
:vartype ingress_bytes_transferred: long
:param peer: The reference to peerings resource.
:type peer: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_local_azure_ip_address: Use private local Azure IP for the connection.
:type use_local_azure_ip_address: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param traffic_selector_policies: The Traffic Selector Policies to be considered by this
connection.
:type traffic_selector_policies:
list[~azure.mgmt.network.v2020_04_01.models.TrafficSelectorPolicy]
:ivar resource_guid: The resource GUID property of the virtual network gateway connection
resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network gateway connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding.
:type express_route_gateway_bypass: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_network_gateway1': {'required': True},
'connection_type': {'required': True},
'connection_status': {'readonly': True},
'tunnel_connection_status': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkGateway'},
'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkGateway'},
'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'LocalNetworkGateway'},
'connection_type': {'key': 'properties.connectionType', 'type': 'str'},
'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'dpd_timeout_seconds': {'key': 'properties.dpdTimeoutSeconds', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'peer': {'key': 'properties.peer', 'type': 'SubResource'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'traffic_selector_policies': {'key': 'properties.trafficSelectorPolicies', 'type': '[TrafficSelectorPolicy]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnection, self).__init__(**kwargs)
self.etag = None
self.authorization_key = kwargs.get('authorization_key', None)
self.virtual_network_gateway1 = kwargs['virtual_network_gateway1']
self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None)
self.local_network_gateway2 = kwargs.get('local_network_gateway2', None)
self.connection_type = kwargs['connection_type']
self.connection_protocol = kwargs.get('connection_protocol', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.dpd_timeout_seconds = kwargs.get('dpd_timeout_seconds', None)
self.shared_key = kwargs.get('shared_key', None)
self.connection_status = None
self.tunnel_connection_status = None
self.egress_bytes_transferred = None
self.ingress_bytes_transferred = None
self.peer = kwargs.get('peer', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.traffic_selector_policies = kwargs.get('traffic_selector_policies', None)
self.resource_guid = None
self.provisioning_state = None
self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None)
class VirtualNetworkGatewayConnectionListEntity(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param authorization_key: The authorizationKey.
:type authorization_key: str
:param virtual_network_gateway1: Required. The reference to virtual network gateway resource.
:type virtual_network_gateway1:
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkConnectionGatewayReference
:param virtual_network_gateway2: The reference to virtual network gateway resource.
:type virtual_network_gateway2:
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkConnectionGatewayReference
:param local_network_gateway2: The reference to local network gateway resource.
:type local_network_gateway2:
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkConnectionGatewayReference
:param connection_type: Required. Gateway connection type. Possible values include: "IPsec",
"Vnet2Vnet", "ExpressRoute", "VPNClient".
:type connection_type: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionType
:param connection_protocol: Connection protocol used for this connection. Possible values
include: "IKEv2", "IKEv1".
:type connection_protocol: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionProtocol
:param routing_weight: The routing weight.
:type routing_weight: int
:param shared_key: The IPSec shared key.
:type shared_key: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar tunnel_connection_status: Collection of all tunnels' connection health status.
:vartype tunnel_connection_status:
list[~azure.mgmt.network.v2020_04_01.models.TunnelConnectionHealth]
:ivar egress_bytes_transferred: The egress bytes transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes transferred in this connection.
:vartype ingress_bytes_transferred: long
:param peer: The reference to peerings resource.
:type peer: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param traffic_selector_policies: The Traffic Selector Policies to be considered by this
connection.
:type traffic_selector_policies:
list[~azure.mgmt.network.v2020_04_01.models.TrafficSelectorPolicy]
:ivar resource_guid: The resource GUID property of the virtual network gateway connection
resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network gateway connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding.
:type express_route_gateway_bypass: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_network_gateway1': {'required': True},
'connection_type': {'required': True},
'connection_status': {'readonly': True},
'tunnel_connection_status': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkConnectionGatewayReference'},
'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'connection_type': {'key': 'properties.connectionType', 'type': 'str'},
'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'peer': {'key': 'properties.peer', 'type': 'SubResource'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'traffic_selector_policies': {'key': 'properties.trafficSelectorPolicies', 'type': '[TrafficSelectorPolicy]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnectionListEntity, self).__init__(**kwargs)
self.etag = None
self.authorization_key = kwargs.get('authorization_key', None)
self.virtual_network_gateway1 = kwargs['virtual_network_gateway1']
self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None)
self.local_network_gateway2 = kwargs.get('local_network_gateway2', None)
self.connection_type = kwargs['connection_type']
self.connection_protocol = kwargs.get('connection_protocol', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.shared_key = kwargs.get('shared_key', None)
self.connection_status = None
self.tunnel_connection_status = None
self.egress_bytes_transferred = None
self.ingress_bytes_transferred = None
self.peer = kwargs.get('peer', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.traffic_selector_policies = kwargs.get('traffic_selector_policies', None)
self.resource_guid = None
self.provisioning_state = None
self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None)
class VirtualNetworkGatewayConnectionListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworkGatewayConnections API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of VirtualNetworkGatewayConnection resources that exists in a resource
group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnection]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGatewayConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewayIPConfiguration(SubResource):
"""IP configuration for virtual network gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2020_04_01.models.IPAllocationMethod
:param subnet: The reference to the subnet resource.
:type subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param public_ip_address: The reference to the public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar private_ip_address: Private IP Address for this gateway.
:vartype private_ip_address: str
:ivar provisioning_state: The provisioning state of the virtual network gateway IP
configuration resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'private_ip_address': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.private_ip_address = None
self.provisioning_state = None
class VirtualNetworkGatewayListConnectionsResult(msrest.serialization.Model):
"""Response for the VirtualNetworkGatewayListConnections API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of VirtualNetworkGatewayConnection resources that exists in a resource
group.
:type value:
list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionListEntity]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGatewayConnectionListEntity]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayListConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewayListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworkGateways API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of VirtualNetworkGateway resources that exists in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGateway]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewaySku(msrest.serialization.Model):
"""VirtualNetworkGatewaySku details.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Gateway SKU name. Possible values include: "Basic", "HighPerformance", "Standard",
"UltraPerformance", "VpnGw1", "VpnGw2", "VpnGw3", "VpnGw4", "VpnGw5", "VpnGw1AZ", "VpnGw2AZ",
"VpnGw3AZ", "VpnGw4AZ", "VpnGw5AZ", "ErGw1AZ", "ErGw2AZ", "ErGw3AZ".
:type name: str or ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewaySkuName
:param tier: Gateway SKU tier. Possible values include: "Basic", "HighPerformance", "Standard",
"UltraPerformance", "VpnGw1", "VpnGw2", "VpnGw3", "VpnGw4", "VpnGw5", "VpnGw1AZ", "VpnGw2AZ",
"VpnGw3AZ", "VpnGw4AZ", "VpnGw5AZ", "ErGw1AZ", "ErGw2AZ", "ErGw3AZ".
:type tier: str or ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewaySkuTier
:ivar capacity: The capacity.
:vartype capacity: int
"""
_validation = {
'capacity': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'capacity': {'key': 'capacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.capacity = None
class VirtualNetworkListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworks API service call.
:param value: A list of VirtualNetwork resources in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetwork]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetwork]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkListUsageResult(msrest.serialization.Model):
"""Response for the virtual networks GetUsage API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: VirtualNetwork usage stats.
:vartype value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkUsage]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkUsage]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkListUsageResult, self).__init__(**kwargs)
self.value = None
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkPeering(SubResource):
"""Peerings in a virtual network resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param allow_virtual_network_access: Whether the VMs in the local virtual network space would
be able to access the VMs in remote virtual network space.
:type allow_virtual_network_access: bool
:param allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the local virtual
network will be allowed/disallowed in remote virtual network.
:type allow_forwarded_traffic: bool
:param allow_gateway_transit: If gateway links can be used in remote virtual networking to link
to this virtual network.
:type allow_gateway_transit: bool
:param use_remote_gateways: If remote gateways can be used on this virtual network. If the flag
is set to true, and allowGatewayTransit on remote peering is also true, virtual network will
use gateways of remote virtual network for transit. Only one peering can have this flag set to
true. This flag cannot be set if virtual network already has a gateway.
:type use_remote_gateways: bool
:param remote_virtual_network: The reference to the remote virtual network. The remote virtual
network can be in the same or different region (preview). See here to register for the preview
and learn more
(https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering).
:type remote_virtual_network: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param remote_address_space: The reference to the remote virtual network address space.
:type remote_address_space: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param peering_state: The status of the virtual network peering. Possible values include:
"Initiated", "Connected", "Disconnected".
:type peering_state: str or ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkPeeringState
:ivar provisioning_state: The provisioning state of the virtual network peering resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'},
'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'},
'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'},
'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'},
'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'},
'remote_address_space': {'key': 'properties.remoteAddressSpace', 'type': 'AddressSpace'},
'peering_state': {'key': 'properties.peeringState', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.allow_virtual_network_access = kwargs.get('allow_virtual_network_access', None)
self.allow_forwarded_traffic = kwargs.get('allow_forwarded_traffic', None)
self.allow_gateway_transit = kwargs.get('allow_gateway_transit', None)
self.use_remote_gateways = kwargs.get('use_remote_gateways', None)
self.remote_virtual_network = kwargs.get('remote_virtual_network', None)
self.remote_address_space = kwargs.get('remote_address_space', None)
self.peering_state = kwargs.get('peering_state', None)
self.provisioning_state = None
class VirtualNetworkPeeringListResult(msrest.serialization.Model):
"""Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual network.
:param value: The peerings in a virtual network.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkPeering]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkPeeringListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkTap(Resource):
"""Virtual Network Tap resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar network_interface_tap_configurations: Specifies the list of resource IDs for the network
interface IP configuration that needs to be tapped.
:vartype network_interface_tap_configurations:
list[~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceTapConfiguration]
:ivar resource_guid: The resource GUID property of the virtual network tap resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network tap resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param destination_network_interface_ip_configuration: The reference to the private IP Address
of the collector nic that will receive the tap.
:type destination_network_interface_ip_configuration:
~azure.mgmt.network.v2020_04_01.models.NetworkInterfaceIPConfiguration
:param destination_load_balancer_front_end_ip_configuration: The reference to the private IP
address on the internal Load Balancer that will receive the tap.
:type destination_load_balancer_front_end_ip_configuration:
~azure.mgmt.network.v2020_04_01.models.FrontendIPConfiguration
:param destination_port: The VXLAN destination port that will receive the tapped traffic.
:type destination_port: int
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'network_interface_tap_configurations': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'network_interface_tap_configurations': {'key': 'properties.networkInterfaceTapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'destination_network_interface_ip_configuration': {'key': 'properties.destinationNetworkInterfaceIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'destination_load_balancer_front_end_ip_configuration': {'key': 'properties.destinationLoadBalancerFrontEndIPConfiguration', 'type': 'FrontendIPConfiguration'},
'destination_port': {'key': 'properties.destinationPort', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkTap, self).__init__(**kwargs)
self.etag = None
self.network_interface_tap_configurations = None
self.resource_guid = None
self.provisioning_state = None
self.destination_network_interface_ip_configuration = kwargs.get('destination_network_interface_ip_configuration', None)
self.destination_load_balancer_front_end_ip_configuration = kwargs.get('destination_load_balancer_front_end_ip_configuration', None)
self.destination_port = kwargs.get('destination_port', None)
class VirtualNetworkTapListResult(msrest.serialization.Model):
"""Response for ListVirtualNetworkTap API service call.
:param value: A list of VirtualNetworkTaps in a resource group.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualNetworkTap]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkTap]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkTapListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkUsage(msrest.serialization.Model):
"""Usage details for subnet.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar current_value: Indicates number of IPs used from the Subnet.
:vartype current_value: float
:ivar id: Subnet identifier.
:vartype id: str
:ivar limit: Indicates the size of the subnet.
:vartype limit: float
:ivar name: The name containing common and localized value for usage.
:vartype name: ~azure.mgmt.network.v2020_04_01.models.VirtualNetworkUsageName
:ivar unit: Usage units. Returns 'Count'.
:vartype unit: str
"""
_validation = {
'current_value': {'readonly': True},
'id': {'readonly': True},
'limit': {'readonly': True},
'name': {'readonly': True},
'unit': {'readonly': True},
}
_attribute_map = {
'current_value': {'key': 'currentValue', 'type': 'float'},
'id': {'key': 'id', 'type': 'str'},
'limit': {'key': 'limit', 'type': 'float'},
'name': {'key': 'name', 'type': 'VirtualNetworkUsageName'},
'unit': {'key': 'unit', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkUsage, self).__init__(**kwargs)
self.current_value = None
self.id = None
self.limit = None
self.name = None
self.unit = None
class VirtualNetworkUsageName(msrest.serialization.Model):
"""Usage strings container.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar localized_value: Localized subnet size and usage string.
:vartype localized_value: str
:ivar value: Subnet size and usage string.
:vartype value: str
"""
_validation = {
'localized_value': {'readonly': True},
'value': {'readonly': True},
}
_attribute_map = {
'localized_value': {'key': 'localizedValue', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkUsageName, self).__init__(**kwargs)
self.localized_value = None
self.value = None
class VirtualRouter(Resource):
"""VirtualRouter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_router_asn: VirtualRouter ASN.
:type virtual_router_asn: long
:param virtual_router_ips: VirtualRouter IPs.
:type virtual_router_ips: list[str]
:param hosted_subnet: The Subnet on which VirtualRouter is hosted.
:type hosted_subnet: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param hosted_gateway: The Gateway on which VirtualRouter is hosted.
:type hosted_gateway: ~azure.mgmt.network.v2020_04_01.models.SubResource
:ivar peerings: List of references to VirtualRouterPeerings.
:vartype peerings: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_router_asn': {'maximum': 4294967295, 'minimum': 0},
'peerings': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_router_asn': {'key': 'properties.virtualRouterAsn', 'type': 'long'},
'virtual_router_ips': {'key': 'properties.virtualRouterIps', 'type': '[str]'},
'hosted_subnet': {'key': 'properties.hostedSubnet', 'type': 'SubResource'},
'hosted_gateway': {'key': 'properties.hostedGateway', 'type': 'SubResource'},
'peerings': {'key': 'properties.peerings', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualRouter, self).__init__(**kwargs)
self.etag = None
self.virtual_router_asn = kwargs.get('virtual_router_asn', None)
self.virtual_router_ips = kwargs.get('virtual_router_ips', None)
self.hosted_subnet = kwargs.get('hosted_subnet', None)
self.hosted_gateway = kwargs.get('hosted_gateway', None)
self.peerings = None
self.provisioning_state = None
class VirtualRouterListResult(msrest.serialization.Model):
"""Response for ListVirtualRouters API service call.
:param value: List of Virtual Routers.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualRouter]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualRouter]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualRouterListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualRouterPeering(SubResource):
"""Virtual Router Peering resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the virtual router peering that is unique within a virtual router.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Peering type.
:vartype type: str
:param peer_asn: Peer ASN.
:type peer_asn: long
:param peer_ip: Peer IP.
:type peer_ip: str
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'peer_asn': {'maximum': 4294967295, 'minimum': 0},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'peer_asn': {'key': 'properties.peerAsn', 'type': 'long'},
'peer_ip': {'key': 'properties.peerIp', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualRouterPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.peer_asn = kwargs.get('peer_asn', None)
self.peer_ip = kwargs.get('peer_ip', None)
self.provisioning_state = None
class VirtualRouterPeeringListResult(msrest.serialization.Model):
"""Response for ListVirtualRouterPeerings API service call.
:param value: List of VirtualRouterPeerings in a VirtualRouter.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VirtualRouterPeering]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualRouterPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualRouterPeeringListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualWAN(Resource):
"""VirtualWAN Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param disable_vpn_encryption: Vpn encryption to be disabled or not.
:type disable_vpn_encryption: bool
:ivar virtual_hubs: List of VirtualHubs in the VirtualWAN.
:vartype virtual_hubs: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar vpn_sites: List of VpnSites in the VirtualWAN.
:vartype vpn_sites: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:param allow_branch_to_branch_traffic: True if branch to branch traffic is allowed.
:type allow_branch_to_branch_traffic: bool
:param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is allowed.
:type allow_vnet_to_vnet_traffic: bool
:ivar office365_local_breakout_category: The office local breakout category. Possible values
include: "Optimize", "OptimizeAndAllow", "All", "None".
:vartype office365_local_breakout_category: str or
~azure.mgmt.network.v2020_04_01.models.OfficeTrafficCategory
:ivar provisioning_state: The provisioning state of the virtual WAN resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param type_properties_type: The type of the VirtualWAN.
:type type_properties_type: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_hubs': {'readonly': True},
'vpn_sites': {'readonly': True},
'office365_local_breakout_category': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'},
'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'},
'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'},
'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'},
'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'},
'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'type_properties_type': {'key': 'properties.type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualWAN, self).__init__(**kwargs)
self.etag = None
self.disable_vpn_encryption = kwargs.get('disable_vpn_encryption', None)
self.virtual_hubs = None
self.vpn_sites = None
self.allow_branch_to_branch_traffic = kwargs.get('allow_branch_to_branch_traffic', None)
self.allow_vnet_to_vnet_traffic = kwargs.get('allow_vnet_to_vnet_traffic', None)
self.office365_local_breakout_category = None
self.provisioning_state = None
self.type_properties_type = kwargs.get('type_properties_type', None)
class VirtualWanSecurityProvider(msrest.serialization.Model):
"""Collection of SecurityProviders.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Name of the security provider.
:type name: str
:param url: Url of the security provider.
:type url: str
:ivar type: Name of the security provider. Possible values include: "External", "Native".
:vartype type: str or ~azure.mgmt.network.v2020_04_01.models.VirtualWanSecurityProviderType
"""
_validation = {
'type': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualWanSecurityProvider, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.url = kwargs.get('url', None)
self.type = None
class VirtualWanSecurityProviders(msrest.serialization.Model):
"""Collection of SecurityProviders.
:param supported_providers: List of VirtualWAN security providers.
:type supported_providers:
list[~azure.mgmt.network.v2020_04_01.models.VirtualWanSecurityProvider]
"""
_attribute_map = {
'supported_providers': {'key': 'supportedProviders', 'type': '[VirtualWanSecurityProvider]'},
}
def __init__(
self,
**kwargs
):
super(VirtualWanSecurityProviders, self).__init__(**kwargs)
self.supported_providers = kwargs.get('supported_providers', None)
class VirtualWanVpnProfileParameters(msrest.serialization.Model):
"""Virtual Wan Vpn profile parameters Vpn profile generation.
:param vpn_server_configuration_resource_id: VpnServerConfiguration partial resource uri with
which VirtualWan is associated to.
:type vpn_server_configuration_resource_id: str
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2020_04_01.models.AuthenticationMethod
"""
_attribute_map = {
'vpn_server_configuration_resource_id': {'key': 'vpnServerConfigurationResourceId', 'type': 'str'},
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualWanVpnProfileParameters, self).__init__(**kwargs)
self.vpn_server_configuration_resource_id = kwargs.get('vpn_server_configuration_resource_id', None)
self.authentication_method = kwargs.get('authentication_method', None)
class VM(Resource):
"""Describes a Virtual Machine.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(VM, self).__init__(**kwargs)
class VnetRoute(msrest.serialization.Model):
"""List of routes that control routing from VirtualHub into a virtual network connection.
:param static_routes: List of all Static Routes.
:type static_routes: list[~azure.mgmt.network.v2020_04_01.models.StaticRoute]
"""
_attribute_map = {
'static_routes': {'key': 'staticRoutes', 'type': '[StaticRoute]'},
}
def __init__(
self,
**kwargs
):
super(VnetRoute, self).__init__(**kwargs)
self.static_routes = kwargs.get('static_routes', None)
class VpnClientConfiguration(msrest.serialization.Model):
"""VpnClientConfiguration for P2S client.
:param vpn_client_address_pool: The reference to the address space resource which represents
Address space for P2S VpnClient.
:type vpn_client_address_pool: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param vpn_client_root_certificates: VpnClientRootCertificate for virtual network gateway.
:type vpn_client_root_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnClientRootCertificate]
:param vpn_client_revoked_certificates: VpnClientRevokedCertificate for Virtual network
gateway.
:type vpn_client_revoked_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnClientRevokedCertificate]
:param vpn_client_protocols: VpnClientProtocols for Virtual network gateway.
:type vpn_client_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.VpnClientProtocol]
:param vpn_client_ipsec_policies: VpnClientIpsecPolicies for virtual network gateway P2S
client.
:type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param radius_server_address: The radius server address property of the VirtualNetworkGateway
resource for vpn client connection.
:type radius_server_address: str
:param radius_server_secret: The radius secret property of the VirtualNetworkGateway resource
for vpn client connection.
:type radius_server_secret: str
:param radius_servers: The radiusServers property for multiple radius server configuration.
:type radius_servers: list[~azure.mgmt.network.v2020_04_01.models.RadiusServer]
:param aad_tenant: The AADTenant property of the VirtualNetworkGateway resource for vpn client
connection used for AAD authentication.
:type aad_tenant: str
:param aad_audience: The AADAudience property of the VirtualNetworkGateway resource for vpn
client connection used for AAD authentication.
:type aad_audience: str
:param aad_issuer: The AADIssuer property of the VirtualNetworkGateway resource for vpn client
connection used for AAD authentication.
:type aad_issuer: str
"""
_attribute_map = {
'vpn_client_address_pool': {'key': 'vpnClientAddressPool', 'type': 'AddressSpace'},
'vpn_client_root_certificates': {'key': 'vpnClientRootCertificates', 'type': '[VpnClientRootCertificate]'},
'vpn_client_revoked_certificates': {'key': 'vpnClientRevokedCertificates', 'type': '[VpnClientRevokedCertificate]'},
'vpn_client_protocols': {'key': 'vpnClientProtocols', 'type': '[str]'},
'vpn_client_ipsec_policies': {'key': 'vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'},
'radius_server_address': {'key': 'radiusServerAddress', 'type': 'str'},
'radius_server_secret': {'key': 'radiusServerSecret', 'type': 'str'},
'radius_servers': {'key': 'radiusServers', 'type': '[RadiusServer]'},
'aad_tenant': {'key': 'aadTenant', 'type': 'str'},
'aad_audience': {'key': 'aadAudience', 'type': 'str'},
'aad_issuer': {'key': 'aadIssuer', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConfiguration, self).__init__(**kwargs)
self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None)
self.vpn_client_root_certificates = kwargs.get('vpn_client_root_certificates', None)
self.vpn_client_revoked_certificates = kwargs.get('vpn_client_revoked_certificates', None)
self.vpn_client_protocols = kwargs.get('vpn_client_protocols', None)
self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None)
self.radius_server_address = kwargs.get('radius_server_address', None)
self.radius_server_secret = kwargs.get('radius_server_secret', None)
self.radius_servers = kwargs.get('radius_servers', None)
self.aad_tenant = kwargs.get('aad_tenant', None)
self.aad_audience = kwargs.get('aad_audience', None)
self.aad_issuer = kwargs.get('aad_issuer', None)
class VpnClientConnectionHealth(msrest.serialization.Model):
"""VpnClientConnectionHealth properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar total_ingress_bytes_transferred: Total of the Ingress Bytes Transferred in this P2S Vpn
connection.
:vartype total_ingress_bytes_transferred: long
:ivar total_egress_bytes_transferred: Total of the Egress Bytes Transferred in this connection.
:vartype total_egress_bytes_transferred: long
:param vpn_client_connections_count: The total of p2s vpn clients connected at this time to
this P2SVpnGateway.
:type vpn_client_connections_count: int
:param allocated_ip_addresses: List of allocated ip addresses to the connected p2s vpn clients.
:type allocated_ip_addresses: list[str]
"""
_validation = {
'total_ingress_bytes_transferred': {'readonly': True},
'total_egress_bytes_transferred': {'readonly': True},
}
_attribute_map = {
'total_ingress_bytes_transferred': {'key': 'totalIngressBytesTransferred', 'type': 'long'},
'total_egress_bytes_transferred': {'key': 'totalEgressBytesTransferred', 'type': 'long'},
'vpn_client_connections_count': {'key': 'vpnClientConnectionsCount', 'type': 'int'},
'allocated_ip_addresses': {'key': 'allocatedIpAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealth, self).__init__(**kwargs)
self.total_ingress_bytes_transferred = None
self.total_egress_bytes_transferred = None
self.vpn_client_connections_count = kwargs.get('vpn_client_connections_count', None)
self.allocated_ip_addresses = kwargs.get('allocated_ip_addresses', None)
class VpnClientConnectionHealthDetail(msrest.serialization.Model):
"""VPN client connection health detail.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar vpn_connection_id: The vpn client Id.
:vartype vpn_connection_id: str
:ivar vpn_connection_duration: The duration time of a connected vpn client.
:vartype vpn_connection_duration: long
:ivar vpn_connection_time: The start time of a connected vpn client.
:vartype vpn_connection_time: str
:ivar public_ip_address: The public Ip of a connected vpn client.
:vartype public_ip_address: str
:ivar private_ip_address: The assigned private Ip of a connected vpn client.
:vartype private_ip_address: str
:ivar vpn_user_name: The user name of a connected vpn client.
:vartype vpn_user_name: str
:ivar max_bandwidth: The max band width.
:vartype max_bandwidth: long
:ivar egress_packets_transferred: The egress packets per second.
:vartype egress_packets_transferred: long
:ivar egress_bytes_transferred: The egress bytes per second.
:vartype egress_bytes_transferred: long
:ivar ingress_packets_transferred: The ingress packets per second.
:vartype ingress_packets_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes per second.
:vartype ingress_bytes_transferred: long
:ivar max_packets_per_second: The max packets transferred per second.
:vartype max_packets_per_second: long
"""
_validation = {
'vpn_connection_id': {'readonly': True},
'vpn_connection_duration': {'readonly': True},
'vpn_connection_time': {'readonly': True},
'public_ip_address': {'readonly': True},
'private_ip_address': {'readonly': True},
'vpn_user_name': {'readonly': True},
'max_bandwidth': {'readonly': True},
'egress_packets_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_packets_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'max_packets_per_second': {'readonly': True},
}
_attribute_map = {
'vpn_connection_id': {'key': 'vpnConnectionId', 'type': 'str'},
'vpn_connection_duration': {'key': 'vpnConnectionDuration', 'type': 'long'},
'vpn_connection_time': {'key': 'vpnConnectionTime', 'type': 'str'},
'public_ip_address': {'key': 'publicIpAddress', 'type': 'str'},
'private_ip_address': {'key': 'privateIpAddress', 'type': 'str'},
'vpn_user_name': {'key': 'vpnUserName', 'type': 'str'},
'max_bandwidth': {'key': 'maxBandwidth', 'type': 'long'},
'egress_packets_transferred': {'key': 'egressPacketsTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'},
'ingress_packets_transferred': {'key': 'ingressPacketsTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'},
'max_packets_per_second': {'key': 'maxPacketsPerSecond', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealthDetail, self).__init__(**kwargs)
self.vpn_connection_id = None
self.vpn_connection_duration = None
self.vpn_connection_time = None
self.public_ip_address = None
self.private_ip_address = None
self.vpn_user_name = None
self.max_bandwidth = None
self.egress_packets_transferred = None
self.egress_bytes_transferred = None
self.ingress_packets_transferred = None
self.ingress_bytes_transferred = None
self.max_packets_per_second = None
class VpnClientConnectionHealthDetailListResult(msrest.serialization.Model):
"""List of virtual network gateway vpn client connection health.
:param value: List of vpn client connection health.
:type value: list[~azure.mgmt.network.v2020_04_01.models.VpnClientConnectionHealthDetail]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnClientConnectionHealthDetail]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealthDetailListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class VpnClientIPsecParameters(msrest.serialization.Model):
"""An IPSec parameters for a virtual network gateway P2S connection.
All required parameters must be populated in order to send to Azure.
:param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) lifetime in seconds for P2S client.
:type sa_life_time_seconds: int
:param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) payload size in KB for P2S client..
:type sa_data_size_kilobytes: int
:param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible
values include: "None", "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES128", "GCMAES192",
"GCMAES256".
:type ipsec_encryption: str or ~azure.mgmt.network.v2020_04_01.models.IpsecEncryption
:param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values
include: "MD5", "SHA1", "SHA256", "GCMAES128", "GCMAES192", "GCMAES256".
:type ipsec_integrity: str or ~azure.mgmt.network.v2020_04_01.models.IpsecIntegrity
:param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values
include: "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES256", "GCMAES128".
:type ike_encryption: str or ~azure.mgmt.network.v2020_04_01.models.IkeEncryption
:param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values
include: "MD5", "SHA1", "SHA256", "SHA384", "GCMAES256", "GCMAES128".
:type ike_integrity: str or ~azure.mgmt.network.v2020_04_01.models.IkeIntegrity
:param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values
include: "None", "DHGroup1", "DHGroup2", "DHGroup14", "DHGroup2048", "ECP256", "ECP384",
"DHGroup24".
:type dh_group: str or ~azure.mgmt.network.v2020_04_01.models.DhGroup
:param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values
include: "None", "PFS1", "PFS2", "PFS2048", "ECP256", "ECP384", "PFS24", "PFS14", "PFSMM".
:type pfs_group: str or ~azure.mgmt.network.v2020_04_01.models.PfsGroup
"""
_validation = {
'sa_life_time_seconds': {'required': True},
'sa_data_size_kilobytes': {'required': True},
'ipsec_encryption': {'required': True},
'ipsec_integrity': {'required': True},
'ike_encryption': {'required': True},
'ike_integrity': {'required': True},
'dh_group': {'required': True},
'pfs_group': {'required': True},
}
_attribute_map = {
'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'},
'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'},
'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'},
'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'},
'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'},
'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'},
'dh_group': {'key': 'dhGroup', 'type': 'str'},
'pfs_group': {'key': 'pfsGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientIPsecParameters, self).__init__(**kwargs)
self.sa_life_time_seconds = kwargs['sa_life_time_seconds']
self.sa_data_size_kilobytes = kwargs['sa_data_size_kilobytes']
self.ipsec_encryption = kwargs['ipsec_encryption']
self.ipsec_integrity = kwargs['ipsec_integrity']
self.ike_encryption = kwargs['ike_encryption']
self.ike_integrity = kwargs['ike_integrity']
self.dh_group = kwargs['dh_group']
self.pfs_group = kwargs['pfs_group']
class VpnClientParameters(msrest.serialization.Model):
"""Vpn Client Parameters for package generation.
:param processor_architecture: VPN client Processor Architecture. Possible values include:
"Amd64", "X86".
:type processor_architecture: str or
~azure.mgmt.network.v2020_04_01.models.ProcessorArchitecture
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2020_04_01.models.AuthenticationMethod
:param radius_server_auth_certificate: The public certificate data for the radius server
authentication certificate as a Base-64 encoded string. Required only if external radius
authentication has been configured with EAPTLS authentication.
:type radius_server_auth_certificate: str
:param client_root_certificates: A list of client root certificates public certificate data
encoded as Base-64 strings. Optional parameter for external radius based authentication with
EAPTLS.
:type client_root_certificates: list[str]
"""
_attribute_map = {
'processor_architecture': {'key': 'processorArchitecture', 'type': 'str'},
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
'radius_server_auth_certificate': {'key': 'radiusServerAuthCertificate', 'type': 'str'},
'client_root_certificates': {'key': 'clientRootCertificates', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientParameters, self).__init__(**kwargs)
self.processor_architecture = kwargs.get('processor_architecture', None)
self.authentication_method = kwargs.get('authentication_method', None)
self.radius_server_auth_certificate = kwargs.get('radius_server_auth_certificate', None)
self.client_root_certificates = kwargs.get('client_root_certificates', None)
class VpnClientRevokedCertificate(SubResource):
"""VPN client revoked certificate of virtual network gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param thumbprint: The revoked VPN client certificate thumbprint.
:type thumbprint: str
:ivar provisioning_state: The provisioning state of the VPN client revoked certificate
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientRevokedCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.thumbprint = kwargs.get('thumbprint', None)
self.provisioning_state = None
class VpnClientRootCertificate(SubResource):
"""VPN client root certificate of virtual network gateway.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param public_cert_data: Required. The certificate public data.
:type public_cert_data: str
:ivar provisioning_state: The provisioning state of the VPN client root certificate resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'public_cert_data': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.public_cert_data = kwargs['public_cert_data']
self.provisioning_state = None
class VpnConnection(SubResource):
"""VpnConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param remote_vpn_site: Id of the connected vpn site.
:type remote_vpn_site: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param routing_weight: Routing weight for vpn connection.
:type routing_weight: int
:param dpd_timeout_seconds: The dead peer detection timeout for a vpn connection in seconds.
:type dpd_timeout_seconds: int
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connecting", "Connected", "NotConnected".
:vartype connection_status: str or ~azure.mgmt.network.v2020_04_01.models.VpnConnectionStatus
:param vpn_connection_protocol_type: Connection protocol used for this connection. Possible
values include: "IKEv2", "IKEv1".
:type vpn_connection_protocol_type: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionProtocol
:ivar ingress_bytes_transferred: Ingress bytes transferred.
:vartype ingress_bytes_transferred: long
:ivar egress_bytes_transferred: Egress bytes transferred.
:vartype egress_bytes_transferred: long
:param connection_bandwidth: Expected bandwidth in MBPS.
:type connection_bandwidth: int
:param shared_key: SharedKey for the vpn connection.
:type shared_key: str
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param enable_rate_limiting: EnableBgp flag.
:type enable_rate_limiting: bool
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:param use_local_azure_ip_address: Use local azure ip to initiate connection.
:type use_local_azure_ip_address: bool
:ivar provisioning_state: The provisioning state of the VPN connection resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param vpn_link_connections: List of all vpn site link connections to the gateway.
:type vpn_link_connections: list[~azure.mgmt.network.v2020_04_01.models.VpnSiteLinkConnection]
:param routing_configuration: The Routing Configuration indicating the associated and
propagated route tables on this connection.
:type routing_configuration: ~azure.mgmt.network.v2020_04_01.models.RoutingConfiguration
"""
_validation = {
'etag': {'readonly': True},
'connection_status': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'remote_vpn_site': {'key': 'properties.remoteVpnSite', 'type': 'SubResource'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'dpd_timeout_seconds': {'key': 'properties.dpdTimeoutSeconds', 'type': 'int'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'vpn_connection_protocol_type': {'key': 'properties.vpnConnectionProtocolType', 'type': 'str'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'connection_bandwidth': {'key': 'properties.connectionBandwidth', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'enable_rate_limiting': {'key': 'properties.enableRateLimiting', 'type': 'bool'},
'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'},
'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'vpn_link_connections': {'key': 'properties.vpnLinkConnections', 'type': '[VpnSiteLinkConnection]'},
'routing_configuration': {'key': 'properties.routingConfiguration', 'type': 'RoutingConfiguration'},
}
def __init__(
self,
**kwargs
):
super(VpnConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.remote_vpn_site = kwargs.get('remote_vpn_site', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.dpd_timeout_seconds = kwargs.get('dpd_timeout_seconds', None)
self.connection_status = None
self.vpn_connection_protocol_type = kwargs.get('vpn_connection_protocol_type', None)
self.ingress_bytes_transferred = None
self.egress_bytes_transferred = None
self.connection_bandwidth = kwargs.get('connection_bandwidth', None)
self.shared_key = kwargs.get('shared_key', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.enable_rate_limiting = kwargs.get('enable_rate_limiting', None)
self.enable_internet_security = kwargs.get('enable_internet_security', None)
self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None)
self.provisioning_state = None
self.vpn_link_connections = kwargs.get('vpn_link_connections', None)
self.routing_configuration = kwargs.get('routing_configuration', None)
class VpnDeviceScriptParameters(msrest.serialization.Model):
"""Vpn device configuration script generation parameters.
:param vendor: The vendor for the vpn device.
:type vendor: str
:param device_family: The device family for the vpn device.
:type device_family: str
:param firmware_version: The firmware version for the vpn device.
:type firmware_version: str
"""
_attribute_map = {
'vendor': {'key': 'vendor', 'type': 'str'},
'device_family': {'key': 'deviceFamily', 'type': 'str'},
'firmware_version': {'key': 'firmwareVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnDeviceScriptParameters, self).__init__(**kwargs)
self.vendor = kwargs.get('vendor', None)
self.device_family = kwargs.get('device_family', None)
self.firmware_version = kwargs.get('firmware_version', None)
class VpnGateway(Resource):
"""VpnGateway Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_hub: The VirtualHub to which the gateway belongs.
:type virtual_hub: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param connections: List of all vpn connections to the gateway.
:type connections: list[~azure.mgmt.network.v2020_04_01.models.VpnConnection]
:param bgp_settings: Local network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2020_04_01.models.BgpSettings
:ivar provisioning_state: The provisioning state of the VPN gateway resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param vpn_gateway_scale_unit: The scale unit for this vpn gateway.
:type vpn_gateway_scale_unit: int
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'connections': {'key': 'properties.connections', 'type': '[VpnConnection]'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VpnGateway, self).__init__(**kwargs)
self.etag = None
self.virtual_hub = kwargs.get('virtual_hub', None)
self.connections = kwargs.get('connections', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.provisioning_state = None
self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None)
class VpnLinkBgpSettings(msrest.serialization.Model):
"""BGP settings details for a link.
:param asn: The BGP speaker's ASN.
:type asn: long
:param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker.
:type bgp_peering_address: str
"""
_attribute_map = {
'asn': {'key': 'asn', 'type': 'long'},
'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnLinkBgpSettings, self).__init__(**kwargs)
self.asn = kwargs.get('asn', None)
self.bgp_peering_address = kwargs.get('bgp_peering_address', None)
class VpnLinkProviderProperties(msrest.serialization.Model):
"""List of properties of a link provider.
:param link_provider_name: Name of the link provider.
:type link_provider_name: str
:param link_speed_in_mbps: Link speed.
:type link_speed_in_mbps: int
"""
_attribute_map = {
'link_provider_name': {'key': 'linkProviderName', 'type': 'str'},
'link_speed_in_mbps': {'key': 'linkSpeedInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VpnLinkProviderProperties, self).__init__(**kwargs)
self.link_provider_name = kwargs.get('link_provider_name', None)
self.link_speed_in_mbps = kwargs.get('link_speed_in_mbps', None)
class VpnPacketCaptureStartParameters(msrest.serialization.Model):
"""Start packet capture parameters on virtual network gateway.
:param filter_data: Start Packet capture parameters.
:type filter_data: str
"""
_attribute_map = {
'filter_data': {'key': 'filterData', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnPacketCaptureStartParameters, self).__init__(**kwargs)
self.filter_data = kwargs.get('filter_data', None)
class VpnPacketCaptureStopParameters(msrest.serialization.Model):
"""Stop packet capture parameters.
:param sas_url: SAS url for packet capture on virtual network gateway.
:type sas_url: str
"""
_attribute_map = {
'sas_url': {'key': 'sasUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnPacketCaptureStopParameters, self).__init__(**kwargs)
self.sas_url = kwargs.get('sas_url', None)
class VpnProfileResponse(msrest.serialization.Model):
"""Vpn Profile Response for package generation.
:param profile_url: URL to the VPN profile.
:type profile_url: str
"""
_attribute_map = {
'profile_url': {'key': 'profileUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnProfileResponse, self).__init__(**kwargs)
self.profile_url = kwargs.get('profile_url', None)
class VpnServerConfigRadiusClientRootCertificate(msrest.serialization.Model):
"""Properties of the Radius client root certificate of VpnServerConfiguration.
:param name: The certificate name.
:type name: str
:param thumbprint: The Radius client root certificate thumbprint.
:type thumbprint: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'thumbprint': {'key': 'thumbprint', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfigRadiusClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.thumbprint = kwargs.get('thumbprint', None)
class VpnServerConfigRadiusServerRootCertificate(msrest.serialization.Model):
"""Properties of Radius Server root certificate of VpnServerConfiguration.
:param name: The certificate name.
:type name: str
:param public_cert_data: The certificate public data.
:type public_cert_data: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'public_cert_data': {'key': 'publicCertData', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfigRadiusServerRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.public_cert_data = kwargs.get('public_cert_data', None)
class VpnServerConfiguration(Resource):
"""VpnServerConfiguration Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param name_properties_name: The name of the VpnServerConfiguration that is unique within a
resource group.
:type name_properties_name: str
:param vpn_protocols: VPN protocols for the VpnServerConfiguration.
:type vpn_protocols: list[str or
~azure.mgmt.network.v2020_04_01.models.VpnGatewayTunnelingProtocol]
:param vpn_authentication_types: VPN authentication types for the VpnServerConfiguration.
:type vpn_authentication_types: list[str or
~azure.mgmt.network.v2020_04_01.models.VpnAuthenticationType]
:param vpn_client_root_certificates: VPN client root certificate of VpnServerConfiguration.
:type vpn_client_root_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnServerConfigVpnClientRootCertificate]
:param vpn_client_revoked_certificates: VPN client revoked certificate of
VpnServerConfiguration.
:type vpn_client_revoked_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnServerConfigVpnClientRevokedCertificate]
:param radius_server_root_certificates: Radius Server root certificate of
VpnServerConfiguration.
:type radius_server_root_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnServerConfigRadiusServerRootCertificate]
:param radius_client_root_certificates: Radius client root certificate of
VpnServerConfiguration.
:type radius_client_root_certificates:
list[~azure.mgmt.network.v2020_04_01.models.VpnServerConfigRadiusClientRootCertificate]
:param vpn_client_ipsec_policies: VpnClientIpsecPolicies for VpnServerConfiguration.
:type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param radius_server_address: The radius server address property of the VpnServerConfiguration
resource for point to site client connection.
:type radius_server_address: str
:param radius_server_secret: The radius secret property of the VpnServerConfiguration resource
for point to site client connection.
:type radius_server_secret: str
:param radius_servers: Multiple Radius Server configuration for VpnServerConfiguration.
:type radius_servers: list[~azure.mgmt.network.v2020_04_01.models.RadiusServer]
:param aad_authentication_parameters: The set of aad vpn authentication parameters.
:type aad_authentication_parameters:
~azure.mgmt.network.v2020_04_01.models.AadAuthenticationParameters
:ivar provisioning_state: The provisioning state of the VpnServerConfiguration resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:ivar p2_s_vpn_gateways: List of references to P2SVpnGateways.
:vartype p2_s_vpn_gateways: list[~azure.mgmt.network.v2020_04_01.models.P2SVpnGateway]
:ivar etag_properties_etag: A unique read-only string that changes whenever the resource is
updated.
:vartype etag_properties_etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'p2_s_vpn_gateways': {'readonly': True},
'etag_properties_etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'name_properties_name': {'key': 'properties.name', 'type': 'str'},
'vpn_protocols': {'key': 'properties.vpnProtocols', 'type': '[str]'},
'vpn_authentication_types': {'key': 'properties.vpnAuthenticationTypes', 'type': '[str]'},
'vpn_client_root_certificates': {'key': 'properties.vpnClientRootCertificates', 'type': '[VpnServerConfigVpnClientRootCertificate]'},
'vpn_client_revoked_certificates': {'key': 'properties.vpnClientRevokedCertificates', 'type': '[VpnServerConfigVpnClientRevokedCertificate]'},
'radius_server_root_certificates': {'key': 'properties.radiusServerRootCertificates', 'type': '[VpnServerConfigRadiusServerRootCertificate]'},
'radius_client_root_certificates': {'key': 'properties.radiusClientRootCertificates', 'type': '[VpnServerConfigRadiusClientRootCertificate]'},
'vpn_client_ipsec_policies': {'key': 'properties.vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'},
'radius_server_address': {'key': 'properties.radiusServerAddress', 'type': 'str'},
'radius_server_secret': {'key': 'properties.radiusServerSecret', 'type': 'str'},
'radius_servers': {'key': 'properties.radiusServers', 'type': '[RadiusServer]'},
'aad_authentication_parameters': {'key': 'properties.aadAuthenticationParameters', 'type': 'AadAuthenticationParameters'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'p2_s_vpn_gateways': {'key': 'properties.p2SVpnGateways', 'type': '[P2SVpnGateway]'},
'etag_properties_etag': {'key': 'properties.etag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfiguration, self).__init__(**kwargs)
self.etag = None
self.name_properties_name = kwargs.get('name_properties_name', None)
self.vpn_protocols = kwargs.get('vpn_protocols', None)
self.vpn_authentication_types = kwargs.get('vpn_authentication_types', None)
self.vpn_client_root_certificates = kwargs.get('vpn_client_root_certificates', None)
self.vpn_client_revoked_certificates = kwargs.get('vpn_client_revoked_certificates', None)
self.radius_server_root_certificates = kwargs.get('radius_server_root_certificates', None)
self.radius_client_root_certificates = kwargs.get('radius_client_root_certificates', None)
self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None)
self.radius_server_address = kwargs.get('radius_server_address', None)
self.radius_server_secret = kwargs.get('radius_server_secret', None)
self.radius_servers = kwargs.get('radius_servers', None)
self.aad_authentication_parameters = kwargs.get('aad_authentication_parameters', None)
self.provisioning_state = None
self.p2_s_vpn_gateways = None
self.etag_properties_etag = None
class VpnServerConfigurationsResponse(msrest.serialization.Model):
"""VpnServerConfigurations list associated with VirtualWan Response.
:param vpn_server_configuration_resource_ids: List of VpnServerConfigurations associated with
VirtualWan.
:type vpn_server_configuration_resource_ids: list[str]
"""
_attribute_map = {
'vpn_server_configuration_resource_ids': {'key': 'vpnServerConfigurationResourceIds', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfigurationsResponse, self).__init__(**kwargs)
self.vpn_server_configuration_resource_ids = kwargs.get('vpn_server_configuration_resource_ids', None)
class VpnServerConfigVpnClientRevokedCertificate(msrest.serialization.Model):
"""Properties of the revoked VPN client certificate of VpnServerConfiguration.
:param name: The certificate name.
:type name: str
:param thumbprint: The revoked VPN client certificate thumbprint.
:type thumbprint: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'thumbprint': {'key': 'thumbprint', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfigVpnClientRevokedCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.thumbprint = kwargs.get('thumbprint', None)
class VpnServerConfigVpnClientRootCertificate(msrest.serialization.Model):
"""Properties of VPN client root certificate of VpnServerConfiguration.
:param name: The certificate name.
:type name: str
:param public_cert_data: The certificate public data.
:type public_cert_data: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'public_cert_data': {'key': 'publicCertData', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnServerConfigVpnClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.public_cert_data = kwargs.get('public_cert_data', None)
class VpnSite(Resource):
"""VpnSite Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_wan: The VirtualWAN to which the vpnSite belongs.
:type virtual_wan: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param device_properties: The device properties.
:type device_properties: ~azure.mgmt.network.v2020_04_01.models.DeviceProperties
:param ip_address: The ip-address for the vpn-site.
:type ip_address: str
:param site_key: The key for vpn-site that can be used for connections.
:type site_key: str
:param address_space: The AddressSpace that contains an array of IP address ranges.
:type address_space: ~azure.mgmt.network.v2020_04_01.models.AddressSpace
:param bgp_properties: The set of bgp properties.
:type bgp_properties: ~azure.mgmt.network.v2020_04_01.models.BgpSettings
:ivar provisioning_state: The provisioning state of the VPN site resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:param is_security_site: IsSecuritySite flag.
:type is_security_site: bool
:param vpn_site_links: List of all vpn site links.
:type vpn_site_links: list[~azure.mgmt.network.v2020_04_01.models.VpnSiteLink]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'},
'device_properties': {'key': 'properties.deviceProperties', 'type': 'DeviceProperties'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'site_key': {'key': 'properties.siteKey', 'type': 'str'},
'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'},
'bgp_properties': {'key': 'properties.bgpProperties', 'type': 'BgpSettings'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'is_security_site': {'key': 'properties.isSecuritySite', 'type': 'bool'},
'vpn_site_links': {'key': 'properties.vpnSiteLinks', 'type': '[VpnSiteLink]'},
}
def __init__(
self,
**kwargs
):
super(VpnSite, self).__init__(**kwargs)
self.etag = None
self.virtual_wan = kwargs.get('virtual_wan', None)
self.device_properties = kwargs.get('device_properties', None)
self.ip_address = kwargs.get('ip_address', None)
self.site_key = kwargs.get('site_key', None)
self.address_space = kwargs.get('address_space', None)
self.bgp_properties = kwargs.get('bgp_properties', None)
self.provisioning_state = None
self.is_security_site = kwargs.get('is_security_site', None)
self.vpn_site_links = kwargs.get('vpn_site_links', None)
class VpnSiteId(msrest.serialization.Model):
"""VpnSite Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar vpn_site: The resource-uri of the vpn-site for which config is to be fetched.
:vartype vpn_site: str
"""
_validation = {
'vpn_site': {'readonly': True},
}
_attribute_map = {
'vpn_site': {'key': 'vpnSite', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnSiteId, self).__init__(**kwargs)
self.vpn_site = None
class VpnSiteLink(SubResource):
"""VpnSiteLink Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar type: Resource type.
:vartype type: str
:param link_properties: The link provider properties.
:type link_properties: ~azure.mgmt.network.v2020_04_01.models.VpnLinkProviderProperties
:param ip_address: The ip-address for the vpn-site-link.
:type ip_address: str
:param fqdn: FQDN of vpn-site-link.
:type fqdn: str
:param bgp_properties: The set of bgp properties.
:type bgp_properties: ~azure.mgmt.network.v2020_04_01.models.VpnLinkBgpSettings
:ivar provisioning_state: The provisioning state of the VPN site link resource. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'link_properties': {'key': 'properties.linkProperties', 'type': 'VpnLinkProviderProperties'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'fqdn': {'key': 'properties.fqdn', 'type': 'str'},
'bgp_properties': {'key': 'properties.bgpProperties', 'type': 'VpnLinkBgpSettings'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnSiteLink, self).__init__(**kwargs)
self.etag = None
self.name = kwargs.get('name', None)
self.type = None
self.link_properties = kwargs.get('link_properties', None)
self.ip_address = kwargs.get('ip_address', None)
self.fqdn = kwargs.get('fqdn', None)
self.bgp_properties = kwargs.get('bgp_properties', None)
self.provisioning_state = None
class VpnSiteLinkConnection(SubResource):
"""VpnSiteLinkConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param vpn_site_link: Id of the connected vpn site link.
:type vpn_site_link: ~azure.mgmt.network.v2020_04_01.models.SubResource
:param routing_weight: Routing weight for vpn connection.
:type routing_weight: int
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connecting", "Connected", "NotConnected".
:vartype connection_status: str or ~azure.mgmt.network.v2020_04_01.models.VpnConnectionStatus
:param vpn_connection_protocol_type: Connection protocol used for this connection. Possible
values include: "IKEv2", "IKEv1".
:type vpn_connection_protocol_type: str or
~azure.mgmt.network.v2020_04_01.models.VirtualNetworkGatewayConnectionProtocol
:ivar ingress_bytes_transferred: Ingress bytes transferred.
:vartype ingress_bytes_transferred: long
:ivar egress_bytes_transferred: Egress bytes transferred.
:vartype egress_bytes_transferred: long
:param connection_bandwidth: Expected bandwidth in MBPS.
:type connection_bandwidth: int
:param shared_key: SharedKey for the vpn connection.
:type shared_key: str
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2020_04_01.models.IpsecPolicy]
:param enable_rate_limiting: EnableBgp flag.
:type enable_rate_limiting: bool
:param use_local_azure_ip_address: Use local azure ip to initiate connection.
:type use_local_azure_ip_address: bool
:ivar provisioning_state: The provisioning state of the VPN site link connection resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'connection_status': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'vpn_site_link': {'key': 'properties.vpnSiteLink', 'type': 'SubResource'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'vpn_connection_protocol_type': {'key': 'properties.vpnConnectionProtocolType', 'type': 'str'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'connection_bandwidth': {'key': 'properties.connectionBandwidth', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'enable_rate_limiting': {'key': 'properties.enableRateLimiting', 'type': 'bool'},
'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnSiteLinkConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.vpn_site_link = kwargs.get('vpn_site_link', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.connection_status = None
self.vpn_connection_protocol_type = kwargs.get('vpn_connection_protocol_type', None)
self.ingress_bytes_transferred = None
self.egress_bytes_transferred = None
self.connection_bandwidth = kwargs.get('connection_bandwidth', None)
self.shared_key = kwargs.get('shared_key', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.enable_rate_limiting = kwargs.get('enable_rate_limiting', None)
self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None)
self.provisioning_state = None
class WebApplicationFirewallCustomRule(msrest.serialization.Model):
"""Defines contents of a web application rule.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param name: The name of the resource that is unique within a policy. This name can be used to
access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Required. Priority of the rule. Rules with a lower value will be evaluated
before rules with a higher value.
:type priority: int
:param rule_type: Required. The rule type. Possible values include: "MatchRule", "Invalid".
:type rule_type: str or ~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallRuleType
:param match_conditions: Required. List of match conditions.
:type match_conditions: list[~azure.mgmt.network.v2020_04_01.models.MatchCondition]
:param action: Required. Type of Actions. Possible values include: "Allow", "Block", "Log".
:type action: str or ~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallAction
"""
_validation = {
'name': {'max_length': 128, 'min_length': 0},
'etag': {'readonly': True},
'priority': {'required': True},
'rule_type': {'required': True},
'match_conditions': {'required': True},
'action': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'rule_type': {'key': 'ruleType', 'type': 'str'},
'match_conditions': {'key': 'matchConditions', 'type': '[MatchCondition]'},
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallCustomRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs['priority']
self.rule_type = kwargs['rule_type']
self.match_conditions = kwargs['match_conditions']
self.action = kwargs['action']
class WebApplicationFirewallPolicy(Resource):
"""Defines web application firewall policy.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param policy_settings: The PolicySettings for policy.
:type policy_settings: ~azure.mgmt.network.v2020_04_01.models.PolicySettings
:param custom_rules: The custom rules inside the policy.
:type custom_rules:
list[~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallCustomRule]
:ivar application_gateways: A collection of references to application gateways.
:vartype application_gateways: list[~azure.mgmt.network.v2020_04_01.models.ApplicationGateway]
:ivar provisioning_state: The provisioning state of the web application firewall policy
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_04_01.models.ProvisioningState
:ivar resource_state: Resource status of the policy. Possible values include: "Creating",
"Enabling", "Enabled", "Disabling", "Disabled", "Deleting".
:vartype resource_state: str or
~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallPolicyResourceState
:param managed_rules: Describes the managedRules structure.
:type managed_rules: ~azure.mgmt.network.v2020_04_01.models.ManagedRulesDefinition
:ivar http_listeners: A collection of references to application gateway http listeners.
:vartype http_listeners: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
:ivar path_based_rules: A collection of references to application gateway path rules.
:vartype path_based_rules: list[~azure.mgmt.network.v2020_04_01.models.SubResource]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'application_gateways': {'readonly': True},
'provisioning_state': {'readonly': True},
'resource_state': {'readonly': True},
'http_listeners': {'readonly': True},
'path_based_rules': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'policy_settings': {'key': 'properties.policySettings', 'type': 'PolicySettings'},
'custom_rules': {'key': 'properties.customRules', 'type': '[WebApplicationFirewallCustomRule]'},
'application_gateways': {'key': 'properties.applicationGateways', 'type': '[ApplicationGateway]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'resource_state': {'key': 'properties.resourceState', 'type': 'str'},
'managed_rules': {'key': 'properties.managedRules', 'type': 'ManagedRulesDefinition'},
'http_listeners': {'key': 'properties.httpListeners', 'type': '[SubResource]'},
'path_based_rules': {'key': 'properties.pathBasedRules', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallPolicy, self).__init__(**kwargs)
self.etag = None
self.policy_settings = kwargs.get('policy_settings', None)
self.custom_rules = kwargs.get('custom_rules', None)
self.application_gateways = None
self.provisioning_state = None
self.resource_state = None
self.managed_rules = kwargs.get('managed_rules', None)
self.http_listeners = None
self.path_based_rules = None
class WebApplicationFirewallPolicyListResult(msrest.serialization.Model):
"""Result of the request to list WebApplicationFirewallPolicies. It contains a list of WebApplicationFirewallPolicy objects and a URL link to get the next set of results.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of WebApplicationFirewallPolicies within a resource group.
:vartype value: list[~azure.mgmt.network.v2020_04_01.models.WebApplicationFirewallPolicy]
:ivar next_link: URL to get the next set of WebApplicationFirewallPolicy objects if there are
any.
:vartype next_link: str
"""
_validation = {
'value': {'readonly': True},
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[WebApplicationFirewallPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallPolicyListResult, self).__init__(**kwargs)
self.value = None
self.next_link = None
|
Azure/azure-sdk-for-python
|
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/models/_models.py
|
Python
|
mit
| 848,302
|
raise NotImplementedError("markupbase is not yet implemented in Skulpt")
|
ArcherSys/ArcherSys
|
skulpt/src/lib/markupbase.py
|
Python
|
mit
| 73
|
# -*- coding: utf-8 -*-
"""
:Copyright: 2007-2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
from __future__ import unicode_literals
from unittest import TestCase
from nose2.tools import params
from syslog2irc.irc import Channel
class IrcChannelTestCase(TestCase):
@params(
(Channel('#example'), '#example', None ),
(Channel('#example', password=None), '#example', None ),
(Channel('#headquarters', password='secret'), '#headquarters', 'secret'),
)
def test_irc_channel_creation(self, channel, expected_name, expected_password):
self.assertEqual(channel.name, expected_name)
self.assertEqual(channel.password, expected_password)
|
Emantor/syslog2irc
|
tests/test_irc_channel.py
|
Python
|
mit
| 791
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: omi
# @Date: 2014-08-24 21:51:57
# @Last Modified by: omi
# @Last Modified time: 2015-08-02 20:57:35
'''
网易云音乐 Ui
'''
import hashlib
import re
import curses
import terminalsize
from api import NetEase
from scrollstring import scrollstring, truelen
from storage import Storage
from config import Config
import logger
from utils import notify
log = logger.getLogger(__name__)
try:
import dbus
dbus_activity = True
except ImportError:
dbus_activity = False
log.warn('dbus module not installed.')
log.warn('Osdlyrics Not Available.')
def escape_quote(text):
return text.replace('\'', '\\\'').replace('\'', '\'\'')
class Ui:
def __init__(self):
self.screen = curses.initscr()
self.screen.timeout(100) # the screen refresh every 100ms
# charactor break buffer
curses.cbreak()
self.screen.keypad(1)
self.netease = NetEase()
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
# term resize handling
size = terminalsize.get_terminal_size()
self.x = max(size[0], 10)
self.y = max(size[1], 25)
self.startcol = int(float(self.x) / 5)
self.indented_startcol = max(self.startcol - 3, 0)
self.update_space()
self.lyric = ''
self.now_lyric = ''
self.tlyric = ''
self.storage = Storage()
self.config = Config()
self.newversion = False
def notify(self, summary, song, album, artist):
if summary != 'disable':
body = '%s\nin %s by %s' % (song, album, artist)
content = escape_quote(summary + ': ' + body)
notify(content)
def build_playinfo(self,
song_name,
artist,
album_name,
quality,
start,
pause=False):
curses.noecho()
# refresh top 2 line
self.screen.move(1, 1)
self.screen.clrtoeol()
self.screen.move(2, 1)
self.screen.clrtoeol()
if pause:
self.screen.addstr(1, self.indented_startcol,
'_ _ z Z Z ' + quality, curses.color_pair(3))
else:
self.screen.addstr(1, self.indented_startcol,
'♫ ♪ ♫ ♪ ' + quality, curses.color_pair(3))
self.screen.addstr(
1, min(self.indented_startcol + 18, self.x - 1),
song_name + self.space + artist + ' < ' + album_name + ' >',
curses.color_pair(4))
self.screen.refresh()
def build_process_bar(self, now_playing, total_length, playing_flag,
pause_flag, playing_mode):
if (self.storage.database['player_info']['idx'] >=
len(self.storage.database['player_info']['player_list'])):
return
curses.noecho()
self.screen.move(3, 1)
self.screen.clrtoeol()
self.screen.move(4, 1)
self.screen.clrtoeol()
if not playing_flag:
return
if total_length <= 0:
total_length = 1
if now_playing > total_length or now_playing <= 0:
now_playing = 0
process = '['
for i in range(0, 33):
if i < now_playing / total_length * 33:
if (i + 1) > now_playing / total_length * 33:
if not pause_flag:
process += '>'
continue
process += '='
else:
process += ' '
process += '] '
now_minute = int(now_playing / 60)
if now_minute > 9:
now_minute = str(now_minute)
else:
now_minute = '0' + str(now_minute)
now_second = int(now_playing - int(now_playing / 60) * 60)
if now_second > 9:
now_second = str(now_second)
else:
now_second = '0' + str(now_second)
total_minute = int(total_length / 60)
if total_minute > 9:
total_minute = str(total_minute)
else:
total_minute = '0' + str(total_minute)
total_second = int(total_length - int(total_length / 60) * 60)
if total_second > 9:
total_second = str(total_second)
else:
total_second = '0' + str(total_second)
process += '(' + now_minute + ':' + now_second + '/' + total_minute + ':' + total_second + ')' # NOQA
if playing_mode == 0:
process = '顺序播放 ' + process
elif playing_mode == 1:
process = '顺序循环 ' + process
elif playing_mode == 2:
process = '单曲循环 ' + process
elif playing_mode == 3:
process = '随机播放 ' + process
elif playing_mode == 4:
process = '随机循环 ' + process
else:
pass
self.screen.addstr(3, self.startcol - 2, process, curses.color_pair(1))
song = self.storage.database['songs'][
self.storage.database['player_info']['player_list'][
self.storage.database['player_info']['idx']]]
if 'lyric' not in song.keys() or len(song['lyric']) <= 0:
self.now_lyric = '暂无歌词 ~>_<~ \n'
if dbus_activity and self.config.get_item('osdlyrics'):
self.now_playing = song['song_name'] + ' - ' + song[
'artist'] + '\n'
else:
key = now_minute + ':' + now_second
for line in song['lyric']:
if key in line:
if 'tlyric' not in song.keys() or len(song['tlyric']) <= 0:
self.now_lyric = line
else:
self.now_lyric = line
for tline in song['tlyric']:
if key in tline and self.config.get_item(
'translation'):
self.now_lyric = tline + ' || ' + self.now_lyric # NOQA
self.now_lyric = re.sub('\[.*?\]', '', self.now_lyric)
if dbus_activity and self.config.get_item('osdlyrics'):
try:
bus = dbus.SessionBus().get_object('org.musicbox.Bus', '/')
if self.now_lyric == '暂无歌词 ~>_<~ \n':
bus.refresh_lyrics(self.now_playing,
dbus_interface='local.musicbox.Lyrics')
else:
bus.refresh_lyrics(self.now_lyric,
dbus_interface='local.musicbox.Lyrics')
except Exception as e:
log.error(e)
pass
self.screen.addstr(4, self.startcol - 2, str(self.now_lyric),
curses.color_pair(3))
self.screen.refresh()
def build_loading(self):
self.screen.addstr(7, self.startcol, '享受高品质音乐,loading...',
curses.color_pair(1))
self.screen.refresh()
# start is the timestamp of this function being called
def build_menu(self, datatype, title, datalist, offset, index, step,
start):
# keep playing info in line 1
curses.noecho()
self.screen.move(5, 1)
self.screen.clrtobot()
self.screen.addstr(5, self.startcol, title, curses.color_pair(1))
if len(datalist) == 0:
self.screen.addstr(8, self.startcol, '这里什么都没有 -,-')
else:
if datatype == 'main':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(i - offset + 9,
self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i],
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i])
elif datatype == 'songs' or datatype == 'fmsongs':
iter_range = min(len(datalist), offset + step)
for i in range(offset, iter_range):
# this item is focus
if i == index:
self.screen.addstr(i - offset + 8, 0,
' ' * self.startcol)
lead = '-> ' + str(i) + '. '
self.screen.addstr(i - offset + 8,
self.indented_startcol, lead,
curses.color_pair(2))
name = '{}{}{} < {} >'.format(datalist[i][
'song_name'], self.space, datalist[i][
'artist'], datalist[i]['album_name'])
# the length decides whether to scoll
if truelen(name) < self.x - self.startcol - 1:
self.screen.addstr(
i - offset + 8,
self.indented_startcol + len(lead), name,
curses.color_pair(2))
else:
name = scrollstring(name + ' ', start)
self.screen.addstr(
i - offset + 8,
self.indented_startcol + len(lead), str(name),
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 8, 0,
' ' * self.startcol)
self.screen.addstr(i - offset + 8, self.startcol, str(
str(i) + '. ' + datalist[i]['song_name'] +
self.space + datalist[i][
'artist'] + ' < ' + datalist[i][
'album_name'] + ' >')[:int(self.x * 2)])
self.screen.addstr(iter_range - offset + 9, 0,
' ' * self.x)
elif datatype == 'artists':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 9, self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i]['artists_name']
+ self.space + str(datalist[i]['alias']),
curses.color_pair(2))
else:
self.screen.addstr(
i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i]['artists_name'] +
self.space + datalist[i][
'alias'])
elif datatype == 'albums':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 9, self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i]['albums_name']
+ self.space + datalist[i][
'artists_name'], curses.color_pair(2))
else:
self.screen.addstr(
i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i]['albums_name'] +
self.space + datalist[i][
'artists_name'])
elif datatype == 'playlists':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 9, self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i]['title'],
curses.color_pair(2))
else:
self.screen.addstr(
i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i]['title'])
elif datatype == 'top_playlists':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 9, self.indented_startcol, '-> ' +
str(i) + '. ' + datalist[i]['playlists_name'] +
self.space + datalist[i]['creator_name'],
curses.color_pair(2))
else:
self.screen.addstr(
i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i]['playlists_name'] +
self.space + datalist[i][
'creator_name'])
elif datatype == 'toplists':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(i - offset + 9,
self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i],
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i])
elif datatype in ('playlist_classes', 'playlist_class_detail'):
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(i - offset + 9,
self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i],
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 9, self.startcol,
str(i) + '. ' + datalist[i])
elif datatype == 'djchannels':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 8, self.indented_startcol,
'-> ' + str(i) + '. ' + datalist[i]['song_name'],
curses.color_pair(2))
else:
self.screen.addstr(
i - offset + 8, self.startcol,
str(i) + '. ' + datalist[i]['song_name'])
elif datatype == 'search':
self.screen.move(6, 1)
self.screen.clrtobot()
self.screen.timeout(-1)
self.screen.addstr(8, self.startcol, '选择搜索类型:',
curses.color_pair(1))
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(
i - offset + 10, self.indented_startcol,
'-> ' + str(i) + '.' + datalist[i - 1],
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 10, self.startcol,
str(i) + '.' + datalist[i - 1])
self.screen.timeout(100)
elif datatype == 'help':
for i in range(offset, min(len(datalist), offset + step)):
if i == index:
self.screen.addstr(i - offset + 9,
self.indented_startcol,
'-> ' + str(i) + '. \'' +
(datalist[i][0].upper() +
'\'').ljust(11) + datalist[i][
1] + ' ' + datalist[i][2],
curses.color_pair(2))
else:
self.screen.addstr(i - offset + 9, self.startcol,
str(i) + '. \'' +
(datalist[i][0].upper() +
'\'').ljust(11) + datalist[i][
1] + ' ' + datalist[i][2])
self.screen.addstr(
20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存')
self.screen.addstr(21, 10,
'按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~')
self.screen.addstr(22, self.startcol,
'Build with love to music by omi')
self.screen.refresh()
def build_search(self, stype):
self.screen.timeout(-1)
netease = self.netease
if stype == 'songs':
song_name = self.get_param('搜索歌曲:')
if song_name == '/return':
return []
else:
try:
data = netease.search(song_name, stype=1)
song_ids = []
if 'songs' in data['result']:
if 'mp3Url' in data['result']['songs']:
songs = data['result']['songs']
# if search song result do not has mp3Url
# send ids to get mp3Url
else:
for i in range(0, len(data['result']['songs'])):
song_ids.append(data['result']['songs'][i][
'id'])
songs = netease.songs_detail(song_ids)
return netease.dig_info(songs, 'songs')
except Exception as e:
log.error(e)
return []
elif stype == 'artists':
artist_name = self.get_param('搜索艺术家:')
if artist_name == '/return':
return []
else:
try:
data = netease.search(artist_name, stype=100)
if 'artists' in data['result']:
artists = data['result']['artists']
return netease.dig_info(artists, 'artists')
except Exception as e:
log.error(e)
return []
elif stype == 'albums':
albums_name = self.get_param('搜索专辑:')
if albums_name == '/return':
return []
else:
try:
data = netease.search(albums_name, stype=10)
if 'albums' in data['result']:
albums = data['result']['albums']
return netease.dig_info(albums, 'albums')
except Exception as e:
log.error(e)
return []
elif stype == 'search_playlist':
search_playlist = self.get_param('搜索网易精选集:')
if search_playlist == '/return':
return []
else:
try:
data = netease.search(search_playlist, stype=1000)
if 'playlists' in data['result']:
playlists = data['result']['playlists']
return netease.dig_info(playlists, 'top_playlists')
except Exception as e:
log.error(e)
return []
return []
def build_login(self):
self.build_login_bar()
local_account = self.get_account()
local_password = hashlib.md5(self.get_password()).hexdigest()
login_info = self.netease.login(local_account, local_password)
account = [local_account, local_password]
if login_info['code'] != 200:
x = self.build_login_error()
if x == ord('1'):
return self.build_login()
else:
return -1
else:
return [login_info, account]
def build_login_bar(self):
curses.noecho()
self.screen.move(4, 1)
self.screen.clrtobot()
self.screen.addstr(5, self.startcol, '请输入登录信息(支持手机登陆)',
curses.color_pair(1))
self.screen.addstr(8, self.startcol, '账号:', curses.color_pair(1))
self.screen.addstr(9, self.startcol, '密码:', curses.color_pair(1))
self.screen.move(8, 24)
self.screen.refresh()
def build_login_error(self):
self.screen.move(4, 1)
self.screen.timeout(-1) # disable the screen timeout
self.screen.clrtobot()
self.screen.addstr(8, self.startcol, '艾玛,登录信息好像不对呢 (O_O)#',
curses.color_pair(1))
self.screen.addstr(10, self.startcol, '[1] 再试一次')
self.screen.addstr(11, self.startcol, '[2] 稍后再试')
self.screen.addstr(14, self.startcol, '请键入对应数字:', curses.color_pair(2))
self.screen.refresh()
x = self.screen.getch()
self.screen.timeout(100) # restore the screen timeout
return x
def get_account(self):
self.screen.timeout(-1) # disable the screen timeout
curses.echo()
account = self.screen.getstr(8, self.startcol + 6, 60)
self.screen.timeout(100) # restore the screen timeout
return account
def get_password(self):
self.screen.timeout(-1) # disable the screen timeout
curses.noecho()
password = self.screen.getstr(9, self.startcol + 6, 60)
self.screen.timeout(100) # restore the screen timeout
return password
def get_param(self, prompt_string):
# keep playing info in line 1
curses.echo()
self.screen.move(4, 1)
self.screen.clrtobot()
self.screen.addstr(5, self.startcol, prompt_string,
curses.color_pair(1))
self.screen.refresh()
info = self.screen.getstr(10, self.startcol, 60)
if info == '':
return '/return'
elif info.strip() is '':
return self.get_param(prompt_string)
else:
return info
def update_size(self):
# get terminal size
size = terminalsize.get_terminal_size()
self.x = max(size[0], 10)
self.y = max(size[1], 25)
# update intendations
curses.resizeterm(self.y, self.x)
self.startcol = int(float(self.x) / 5)
self.indented_startcol = max(self.startcol - 3, 0)
self.update_space()
self.screen.clear()
self.screen.refresh()
def update_space(self):
if self.x > 140:
self.space = ' - '
elif self.x > 80:
self.space = ' - '
else:
self.space = ' - '
self.screen.refresh()
|
Catofes/musicbox
|
NEMbox/ui.py
|
Python
|
mit
| 23,861
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "iamhhb.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django # noqa
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
graycarl/iamhhb
|
manage.py
|
Python
|
mit
| 812
|
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from smserver import models
from smserver import smutils
from smserver.chathelper import with_color
from smserver.chatplugin import ChatPlugin
from smserver.models import ranked_chart
from smserver.models.ranked_chart import Diffs
class ChatHelp(ChatPlugin):
command = "help"
helper = "Show help"
def __call__(self, serv, message):
for command, action in sorted(serv.server.chat_commands.items()):
if not action.can(serv):
continue
serv.send_message("/%s: %s" % (command, action.helper), to="me")
class ChatUserListing(ChatPlugin):
command = "users"
helper = "List users"
def __call__(self, serv, message):
users = serv.session.query(models.User).filter_by(online=True)
max_users = serv.server.config.server.get("max_users")
if serv.room:
users = users.filter_by(room_id=serv.room.id)
max_users = serv.room.max_users
users = users.all()
serv.send_message("%s/%s players online" % (len(users), max_users), to="me")
for user in users:
serv.send_message(
"%s (in %s)" % (
user.fullname_colored(serv.conn.room),
user.enum_status.name),
to="me")
class ChatTimestamp(ChatPlugin):
command = "timestamp"
helper = "Enable chat timestamps"
def __call__(self, serv, message):
if serv.conn.chat_timestamp:
serv.conn.chat_timestamp = False
serv.send_message("Chat timestamp disabled", to="me")
else:
serv.send_message("Chat timestamp enabled", to="me")
serv.conn.chat_timestamp = True
for user in serv.active_users:
user.chat_timestamp = serv.conn.chat_timestamp
class ShowOffset(ChatPlugin):
command = "showoffset"
helper = "Enable average offset display after a song"
def __call__(self, serv, message):
for user in serv.active_users:
if user.show_offset:
user.show_offset = False
serv.send_message("Offset diplay disabled", to="me")
else:
user.show_offset = True
serv.send_message("Offset diplay enabled", to="me")
class Profile(ChatPlugin):
command = "profile"
helper = "Display profile information"
def __call__(self, serv, message):
if not message:
for user in serv.active_users:
serv.send_message("Name: %s" % with_color(user.name), to="me")
serv.send_message("XP: %20.0f" % user.xp, to="me")
serv.send_message("Rank: %s" % user.skillrank, to="me")
serv.send_message("Rating: %12.2f" % user.rating, to="me")
else:
user = serv.session.query(models.User).filter_by(name=message).first()
if not user:
serv.send_message("Could not find user %s" % with_color(message), to="me")
else:
serv.send_message("Name: %s" % with_color(user.name), to="me")
serv.send_message("XP: %s" % user.xp, to="me")
serv.send_message("Rank: %s" % user.skillrank, to="me")
serv.send_message("Rating: %12.2f" % user.rating, to="me")
#for skillset in models.ranked_song.Skillsets:
# rating = eval("user.rating_" + skillset.name)
# serv.send_message(skillset.name.capitalize()+": %f" % rating, to="me")
class FriendNotification(ChatPlugin):
command = "friendnotif"
helper = "Enable notifications whenever a friend gets on/off line"
def __call__(self, serv, message):
for user in serv.active_users:
if user.friend_notifications:
user.friend_notifications = False
serv.send_message("Friend notifications disabled", to="me")
else:
user.friend_notifications = True
serv.send_message("Friend notifications enabled", to="me")
#This lags a lot if there are many ranked charts
# class RankedCharts(ChatPlugin):
# command = "rankedcharts"
# helper = "Show all ranked songs"
# def __call__(self, serv, message):
# charts = serv.session.query(models.RankedChart, models.Song.title).join(models.Song).all()
# serv.send_message("Ranked Charts:", to="me")
# for chart in charts:
# serv.send_message("Title: " + chart[1] + " Pack: " + chart[0].pack_name + " Diff: " + Diffs(chart[0].diff).name, to="me")
class AddFriend(ChatPlugin):
command = "addfriend"
helper = "Add a friend. /addfriend user"
def __call__(self, serv, message):
for user in serv.active_users:
if not user:
return
newfriend = serv.session.query(models.User).filter_by(name=message).first()
if not newfriend:
serv.send_message("Unknown user %s" % with_color(message), to="me")
return
if newfriend.name == user.name:
serv.send_message("Cant befriend yourself", to="me")
return
friendships = serv.session.query(models.Friendship).filter( \
((models.Friendship.user1_id == user.id) & (models.Friendship.user2_id == newfriend.id)) | \
(models.Friendship.user2_id == user.id) & (models.Friendship.user1_id == newfriend.id))
if not friendships.first():
serv.session.add(models.Friendship(user1_id = user.id, user2_id = newfriend.id, state = 0))
serv.send_message("Friend request sent to %s" % with_color(message), to="me")
else:
friendships = friendships.all()
if len(friendships) != 1:
if friendship[0].state == 2:
if friendship.user1_id == user.id:
Unignore.__call__(self, serv, message)
friendship = friendships[1]
if friendship[1].state == 2:
if friendship.user1_id == user.id:
Unignore.__call__(self, serv, message)
friendship = friendships[0]
else:
friendship = friendships[0]
if friendship.state == 1:
serv.send_message("%s is already friends with you" % with_color(message), to="me")
return
if friendship.state == 2:
serv.send_message("Cant send %s a friend request" % with_color(message), to="me")
return
if friendship.user1_id == user.id:
serv.send_message("Already sent a friend request to %s" % with_color(message), to="me")
return
friendship.state = 1
serv.send_message("Accepted friend request from %s" % with_color(message), to="me")
serv.session.commit()
class Ignore(ChatPlugin):
command = "ignore"
helper = "Ignore someone(Can't send friend requests or pm). /ignore user"
def __call__(self, serv, message):
for user in serv.active_users:
if not user:
return
newignore = serv.session.query(models.User).filter_by(name=message).first()
if not newignore:
serv.send_message("Unknown user %s" % with_color(message), to="me")
return
if newignore.name == user.name:
serv.send_message("Cant ignore yourself", to="me")
return
friendships = serv.session.query(models.Friendship).filter( \
((models.Friendship.user1_id == user.id) & (models.Friendship.user2_id == newignore.id)) | \
(models.Friendship.user2_id == user.id) & (models.Friendship.user1_id == newignore.id))
friendship = friendships.first()
if not friendship:
serv.session.add(models.Friendship(user1_id = user.id, user2_id = newignore.id, state = 2))
serv.send_message("%s ignored" % with_color(message), to="me")
else:
if friendship.state == 2:
if friendship.user1_id == user.id:
serv.send_message("%s is already ignored" % with_color(message), to="me")
else:
friendshiptwo = friendships.all()
if len(friendshiptwo) > 1:
friendshiptwo = friendshiptwo[1]
if friendshiptwo.user1_id == user.id:
serv.send_message("%s is already ignored" % with_color(message), to="me")
return
serv.session.add(models.Friendship(user1_id = user.id, user2_id = newignore.id, state = 2))
serv.send_message("%s ignored" % with_color(message), to="me")
return
friendship.state = 2
friendship.user1_id = user.id
friendship.user2_id = newignore.id
serv.send_message("%s ignored" % with_color(message), to="me")
serv.session.commit()
class Unignore(ChatPlugin):
command = "unignore"
helper = "Stop ignoring someone. /unignore user"
def __call__(self, serv, message):
for user in serv.active_users:
if not user:
return
newignore = serv.session.query(models.User).filter_by(name=message).first()
if not newignore:
serv.send_message("Unknown user %s" % with_color(message), to="me")
return
friendship = serv.session.query(models.Friendship).filter_by(user1_id = user.id).filter_by(user2_id = newignore.id).filter_by(state = 2).first()
if friendship:
serv.session.delete(friendship)
serv.session.commit()
serv.send_message("%s unignored" % with_color(message), to="me")
return
serv.send_message("%s is not currently ignored. Cant unignore" % with_color(message), to="me")
class Friendlist(ChatPlugin):
command = "friendlist"
helper = "Show friendlist"
def __call__(self, serv, message):
for user in serv.active_users:
if not user:
return
friends = serv.session.query(models.Friendship).filter_by(state = 1).filter((models.Friendship.user1_id == user.id) | models.Friendship.user2_id == user.id).all()
friendsStr = ""
for friend in friends:
if friend.user1_id == user.id:
frienduser = serv.session.query(models.User).filter_by(id = friend.user2_id).first()
else:
frienduser = serv.session.query(models.User).filter_by(id = friend.user1_id).first()
friendsStr += frienduser.name + ", "
if friendsStr.endswith(", "):
friendsStr = friendsStr[:-2]
requests = serv.session.query(models.Friendship).filter_by(user2_id = user.id).filter_by(state = 0).all()
requestsStr = ""
for request in requests:
requestsStr += serv.session.query(models.User).filter_by(id=request.user1_id).first().name + ", "
if requestsStr.endswith(", "):
requestsStr = requestsStr[:-2]
requestsoutgoing = serv.session.query(models.Friendship).filter_by(user1_id = user.id).filter_by(state = 0).all()
requestsoutgoingStr = ""
for request in requestsoutgoing:
requestsoutgoingStr += serv.session.query(models.User).filter_by(id=request.user2_id).first().name + ", "
if requestsoutgoingStr.endswith(", "):
requestsoutgoingStr = requestsoutgoingStr[:-2]
ignores = serv.session.query(models.Friendship).filter_by(user1_id = user.id).filter_by(state = 2).all()
ignoresStr = ""
for ignore in ignores:
ignoresStr += serv.session.query(models.User).filter_by(id=ignore.user2_id).first().name + ", "
if ignoresStr.endswith(", "):
ignoresStr = ignoresStr[:-2]
serv.send_message("Friends: %s" % friendsStr, to="me")
serv.send_message("Incoming requests: %s" % requestsStr, to="me")
serv.send_message("Outgoing requests: %s" % requestsoutgoingStr, to="me")
serv.send_message("Ignoring: %s" % ignoresStr, to="me")
class PrivateMessage(ChatPlugin):
command = "pm"
helper = "Send a private message. /pm user message"
def __call__(self, serv, message):
user = models.User.from_ids(serv.conn.users, serv.session)
user = user[0]
#user = serv.session.query(models.User).filter_by(online = True).filter_by(last_ip = serv.conn.ip).first()
if not user:
return
message = message.split(' ', 1)
if len(message) < 2:
serv.send_message("Need a text message to send", to="me")
return
if self.sendpm(serv, user, message[0], message[1]) == False:
if '_' in message[0]:
self.sendpm(serv, user, message[0].replace('_',' '), message[1])
def sendpm(self, serv, user, receptorname, message):
receptor = serv.session.query(models.User).filter_by(online=True).filter_by(name=receptorname).first()
if not receptor:
serv.send_message("Could not find %s online" % with_color(receptorname), to="me")
return False
if receptor.name == user.name:
serv.send_message("Cant pm yourself", to="me")
return False
ignore = serv.session.query(models.Friendship).filter( \
(((models.Friendship.user1_id == user.id) & (models.Friendship.user2_id == receptor.id)) | \
((models.Friendship.user2_id == user.id) & (models.Friendship.user1_id == receptor.id))) & \
(models.Friendship.state == 2)).first()
if ignore:
serv.send_message("Cant send %s a private message" %with_color(receptorname), to="me")
return False
if not receptor:
serv.send_message("Could not find %s online" % with_color(receptorname), to="me")
return False
serv.send_message("To %s : %s" % (with_color(receptor.name), message), to="me")
receptor = serv.server.find_connection(receptor.id)
#if i do what's commented both players get the message
#serv.send_message("From %s : %s" % (with_color(user.name), message), receptor)
receptor.send(smutils.smpacket.SMPacketServerNSCCM(message="From %s : %s" % (with_color(user.name), message)))
return True
|
Nickito12/stepmania-server
|
smserver/chat_commands/general.py
|
Python
|
mit
| 14,861
|
__author__ = 'brandon.corfman'
# Global constants used across the application.
AVERAGED_OVER_ALL_AZIMUTHS = -1
AVERAGED_ON_NON_ZERO_AVS = 0
BY_AZIMUTH = 1
GYPSY_PINK = (0.6745, 0.196, 0.3882) # color coveted by JJS; used for blast volumes
WHITE = (1.0, 1.0, 1.0)
CMPID, R1, R2, R3, Z1, Z2 = range(6)
|
bcorfman/stage
|
const.py
|
Python
|
mit
| 301
|
# --------------------------------------------------------------------------------- #
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #
"""
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget.
Description
===========
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.
:class:`RulerCtrl` has the following characteristics:
- Can be horizontal or vertical;
- 4 built-in formats: integer, real, time and linearDB formats;
- Units (as ``cm``, ``dB``, ``inches``) can be displayed together with the label values;
- Possibility to add a number of "paragraph indicators", small arrows that point at
the current indicator position;
- Customizable background colour, tick colour, label colour;
- Possibility to flip the ruler (i.e. changing the tick alignment);
- Changing individually the indicator colour (requires PIL at the moment);
- Different window borders are supported (``wx.STATIC_BORDER``, ``wx.SUNKEN_BORDER``,
``wx.DOUBLE_BORDER``, ``wx.NO_BORDER``, ``wx.RAISED_BORDER``, ``wx.SIMPLE_BORDER``);
- Logarithmic scale available;
- Possibility to draw a thin line over a selected window when moving an indicator,
which emulates the text editors software.
And a lot more. See the demo for a review of the functionalities.
Usage
=====
Usage example::
import wx
import wx.lib.agw.rulerctrl as RC
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "RulerCtrl Demo")
panel = wx.Panel(self)
text = wx.TextCtrl(panel, -1, "Hello World! wxPython rules", style=wx.TE_MULTILINE)
ruler1 = RC.RulerCtrl(panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER)
ruler2 = RC.RulerCtrl(panel, -1, orient=wx.VERTICAL, style=wx.SUNKEN_BORDER)
mainsizer = wx.BoxSizer(wx.HORIZONTAL)
leftsizer = wx.BoxSizer(wx.VERTICAL)
bottomleftsizer = wx.BoxSizer(wx.HORIZONTAL)
topsizer = wx.BoxSizer(wx.HORIZONTAL)
leftsizer.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
topsizer.Add((39, 0), 0, wx.ADJUST_MINSIZE, 0)
topsizer.Add(ruler1, 1, wx.EXPAND, 0)
leftsizer.Add(topsizer, 0, wx.EXPAND, 0)
bottomleftsizer.Add((10, 0))
bottomleftsizer.Add(ruler2, 0, wx.EXPAND, 0)
bottomleftsizer.Add(text, 1, wx.EXPAND, 0)
leftsizer.Add(bottomleftsizer, 1, wx.EXPAND, 0)
mainsizer.Add(leftsizer, 3, wx.EXPAND, 0)
panel.SetSizer(mainsizer)
# our normal wxApp-derived class, as usual
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Events
======
:class:`RulerCtrl` implements the following events related to indicators:
- ``EVT_INDICATOR_CHANGING``: the user is about to change the position of one indicator;
- ``EVT_INDICATOR_CHANGED``: the user has changed the position of one indicator.
Supported Platforms
===================
:class:`RulerCtrl` has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)
Window Styles
=============
`No particular window styles are available for this class.`
Events Processing
=================
This class processes the following events:
========================== ==================================================
Event Name Description
========================== ==================================================
``EVT_INDICATOR_CHANGED`` The user has changed the indicator value.
``EVT_INDICATOR_CHANGING`` The user is about to change the indicator value.
========================== ==================================================
License And Version
===================
:class:`RulerCtrl` is distributed under the wxPython license.
Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
Version 0.3
"""
__docformat__ = "epytext"
import wx
import math
import cStringIO, zlib
# Try to import PIL, if possible.
# This is used only to change the colour for an indicator arrow.
_hasPIL = False
try:
import Image
_hasPIL = True
except:
pass
# Built-in formats
IntFormat = 1
""" Integer format. """
RealFormat = 2
""" Real format. """
TimeFormat = 3
""" Time format. """
LinearDBFormat = 4
""" Linear DB format. """
HHMMSS_Format = 5
""" HHMMSS format. """
# Events
wxEVT_INDICATOR_CHANGING = wx.NewEventType()
wxEVT_INDICATOR_CHANGED = wx.NewEventType()
EVT_INDICATOR_CHANGING = wx.PyEventBinder(wxEVT_INDICATOR_CHANGING, 2)
""" The user is about to change the indicator value. """
EVT_INDICATOR_CHANGED = wx.PyEventBinder(wxEVT_INDICATOR_CHANGED, 2)
""" The user has changed the indicator value. """
# Some accessor functions
#----------------------------------------------------------------------
def GetIndicatorData():
""" Returns the image indicator as a decompressed stream of characters. """
return zlib.decompress(
'x\xda\x01x\x01\x87\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\n\x00\
\x00\x00\n\x08\x06\x00\x00\x00\x8d2\xcf\xbd\x00\x00\x00\x04sBIT\x08\x08\x08\
\x08|\x08d\x88\x00\x00\x01/IDAT\x18\x95m\xceO(\x83q\x1c\xc7\xf1\xf7\xef\xf9\
\xcd\xf6D6\xca\x1c\xc8\x9f\x14\'J-\xc4A9(9(-\xe5 \xed\xe4\xe2\xe2\xb2\x928\
\xb9\xec\xc2\x01\x17.\x0e\xe4\xe6B\xed\xb2\x1c\xdc$5\x97\xf9S\xb3\x14+\x0eO\
\xdb\xccZ\x9e\xfd\xf9\xba\x98E{\x1d\xbf\xbd\xfb\xf4U\x00\x18\x9d\xc3\xad\x1d\
\xa1+\xa7S\x15\xf8\xa1\xb5i\xbc\xc4\xd7\x0f\xca\xc5\xd82U3[\x97\xb1\x82\xc4S\
"\x89\xb4\xc8SZ\xc4\xb2E\xfa\x06CR)\x1c\x00\xb8\x8cb"-|\x94@\x01\x0e\r\xee&\
\xf8\x12\xc5\xdf\xd0\xd4\xf2\xf6i\x90/\x82\xe9\x82\xdb\xe72\xa7\xe7%\x92\x99\
\xdfA\xb4j\x9b]\xa5\xaek\xbag|\xaa\xdd\xca)\xceb\x10\xbe\x87\xacm VT\xd0N\
\x0f\xf9\xd7\x94\xd6\xde\xb1\xdd\xf9\xcdm_\x83\xdb\x81\x95W\x88\x02\xad\x159\
\x01\xcc!U2}\xa3$\x0f\x1dZR\xd1\xfd\xbb\x9b\xc7\x89\xc99\x7f\xb7\xb7\xd1\x00\
\xc0.B\xbe\xac\xc8\xbe?P\x8e\x8c\x1ccg\x02\xd5\x1f\x9a\x07\xf6\x82a[6.D\xfc\
\'"\x9e\xc0\xb5\xa0\xeb\xd7\xa8\xc9\xdd\xbf\xb3pdI\xefRD\xc0\x08\xd6\x8e*\\-\
+\xa0\x17\xff\x9f\xbf\x01{\xb5t\x9e\x99]a\x97\x00\x00\x00\x00IEND\xaeB`\x82G\
\xbf\xa8>' )
def GetIndicatorBitmap():
""" Returns the image indicator as a :class:`Bitmap`. """
return wx.BitmapFromImage(GetIndicatorImage())
def GetIndicatorImage():
""" Returns the image indicator as a :class:`Image`. """
stream = cStringIO.StringIO(GetIndicatorData())
return wx.ImageFromStream(stream)
def MakePalette(tr, tg, tb):
"""
Creates a palette to be applied on an image based on input colour.
:param `tr`: the red intensity of the input colour;
:param `tg`: the green intensity of the input colour;
:param `tb`: the blue intensity of the input colour.
"""
l = []
for i in range(255):
l.extend([tr*i / 255, tg*i / 255, tb*i / 255])
return l
def ConvertWXToPIL(bmp):
"""
Converts a :class:`Image` into a PIL image.
:param `bmp`: an instance of :class:`Image`.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
width = bmp.GetWidth()
height = bmp.GetHeight()
img = Image.fromstring("RGBA", (width, height), bmp.GetData())
return img
def ConvertPILToWX(pil, alpha=True):
"""
Converts a PIL image into a :class:`Image`.
:param `pil`: a PIL image;
:param `alpha`: ``True`` if the image contains alpha transparency, ``False``
otherwise.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
if alpha:
image = apply(wx.EmptyImage, pil.size)
image.SetData(pil.convert("RGB").tostring())
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
new_image = pil.convert('RGB')
data = new_image.tostring()
image.SetData(data)
return image
# ---------------------------------------------------------------------------- #
# Class RulerCtrlEvent
# ---------------------------------------------------------------------------- #
class RulerCtrlEvent(wx.PyCommandEvent):
"""
Represent details of the events that the :class:`RulerCtrl` object sends.
"""
def __init__(self, eventType, eventId=1):
"""
Default class constructor.
:param `eventType`: the event type;
:param `eventId`: the event identifier.
"""
wx.PyCommandEvent.__init__(self, eventType, eventId)
def SetValue(self, value):
"""
Sets the event value.
:param `value`: the new indicator position.
"""
self._value = value
def GetValue(self):
""" Returns the event value. """
return self._value
def SetOldValue(self, oldValue):
"""
Sets the event old value.
:param `value`: the old indicator position.
"""
self._oldValue = oldValue
def GetOldValue(self):
""" Returns the event old value. """
return self._oldValue
# ---------------------------------------------------------------------------- #
# Class Label
# ---------------------------------------------------------------------------- #
class Label(object):
"""
Auxilary class. Just holds information about a label in :class:`RulerCtrl`.
"""
def __init__(self, pos=-1, lx=-1, ly=-1, text=""):
"""
Default class constructor.
:param `pos`: the indicator position;
:param `lx`: the indicator `x` coordinate;
:param `ly`: the indicator `y` coordinate;
:param `text`: the label text.
"""
self.pos = pos
self.lx = lx
self.ly = ly
self.text = text
# ---------------------------------------------------------------------------- #
# Class Indicator
# ---------------------------------------------------------------------------- #
class Indicator(object):
"""
This class holds all the information about a single indicator inside :class:`RulerCtrl`.
You should not call this class directly. Use::
ruler.AddIndicator(id, value)
to add an indicator to your :class:`RulerCtrl`.
"""
def __init__(self, parent, id=wx.ID_ANY, value=0):
"""
Default class constructor.
:param `parent`: the parent window, an instance of :class:`RulerCtrl`;
:param `id`: the indicator identifier;
:param `value`: the initial value of the indicator.
"""
self._parent = parent
if id == wx.ID_ANY:
id = wx.NewId()
self._id = id
self._colour = None
self.RotateImage(GetIndicatorImage())
self.SetValue(value)
def GetPosition(self):
""" Returns the position at which we should draw the indicator bitmap. """
orient = self._parent._orientation
flip = self._parent._flip
left, top, right, bottom = self._parent.GetBounds()
minval = self._parent._min
maxval = self._parent._max
value = self._value
if self._parent._log:
value = math.log10(value)
maxval = math.log10(maxval)
minval = math.log10(minval)
pos = float(value-minval)/abs(maxval - minval)
if orient == wx.HORIZONTAL:
xpos = int(pos*right) - self._img.GetWidth()/2
if flip:
ypos = top
else:
ypos = bottom - self._img.GetHeight()
else:
ypos = int(pos*bottom) - self._img.GetHeight()/2
if flip:
xpos = left
else:
xpos = right - self._img.GetWidth()
return xpos, ypos
def GetImageSize(self):
""" Returns the indicator bitmap size. """
return self._img.GetWidth(), self._img.GetHeight()
def GetRect(self):
""" Returns the indicator client rectangle. """
return self._rect
def RotateImage(self, img=None):
"""
Rotates the default indicator bitmap.
:param `img`: if not ``None``, the indicator image.
"""
if img is None:
img = GetIndicatorImage()
orient = self._parent._orientation
flip = self._parent._flip
left, top, right, bottom = self._parent.GetBounds()
if orient == wx.HORIZONTAL:
if flip:
img = img.Rotate(math.pi, (5, 5), True)
else:
if flip:
img = img.Rotate(-math.pi/2, (5, 5), True)
else:
img = img.Rotate(math.pi/2, (5, 5), True)
self._img = img
def SetValue(self, value):
"""
Sets the indicator value.
:param `value`: the new indicator value.
"""
if value < self._parent._min:
value = self._parent._min
if value > self._parent._max:
value = self._parent._max
self._value = value
self._rect = wx.Rect()
self._parent.Refresh()
def GetValue(self):
""" Returns the indicator value. """
return self._value
def Draw(self, dc):
"""
Actually draws the indicator.
:param `dc`: an instance of :class:`DC`.
"""
xpos, ypos = self.GetPosition()
bmp = wx.BitmapFromImage(self._img)
dc.DrawBitmap(bmp, xpos, ypos, True)
self._rect = wx.Rect(xpos, ypos, self._img.GetWidth(), self._img.GetHeight())
def GetId(self):
""" Returns the indicator id. """
return self._id
def SetColour(self, colour):
"""
Sets the indicator colour.
:param `colour`: the new indicator colour, an instance of :class:`Colour`.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
if not _hasPIL:
return
palette = colour.Red(), colour.Green(), colour.Blue()
img = ConvertWXToPIL(GetIndicatorBitmap())
l = MakePalette(*palette)
# The Palette Can Be Applied Only To "L" And "P" Images, Not "RGBA"
img = img.convert("L")
# Apply The New Palette
img.putpalette(l)
# Convert The Image Back To RGBA
img = img.convert("RGBA")
img = ConvertPILToWX(img)
self.RotateImage(img)
self._parent.Refresh()
# ---------------------------------------------------------------------------- #
# Class RulerCtrl
# ---------------------------------------------------------------------------- #
class RulerCtrl(wx.PyPanel):
"""
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.STATIC_BORDER, orient=wx.HORIZONTAL):
"""
Default class constructor.
:param `parent`: parent window. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the window style;
:param `orient`: sets the orientation of the :class:`RulerCtrl`, and can be either
``wx.HORIZONTAL`` of ``wx.VERTICAL``.
"""
wx.PyPanel.__init__(self, parent, id, pos, size, style)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
width, height = size
self._min = 0.0
self._max = 10.0
self._orientation = orient
self._spacing = 5
self._hassetspacing = False
self._format = RealFormat
self._flip = False
self._log = False
self._labeledges = False
self._units = ""
self._drawingparent = None
self._drawingpen = wx.Pen(wx.BLACK, 2)
self._left = -1
self._top = -1
self._right = -1
self._bottom = -1
self._major = 1
self._minor = 1
self._indicators = []
self._currentIndicator = None
fontsize = 10
if wx.Platform == "__WXMSW__":
fontsize = 8
self._minorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.NORMAL)
self._majorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.BOLD)
if wx.Platform == "__WXMAC__":
self._minorfont.SetNoAntiAliasing(True)
self._majorfont.SetNoAntiAliasing(True)
self._bits = []
self._userbits = []
self._userbitlen = 0
self._tickmajor = True
self._tickminor = True
self._timeformat = IntFormat
self._labelmajor = True
self._labelminor = True
self._tickpen = wx.Pen(wx.BLACK)
self._textcolour = wx.BLACK
self._background = wx.WHITE
self._valid = False
self._state = 0
self._style = style
self._orientation = orient
wbound, hbound = self.CheckStyle()
if orient & wx.VERTICAL:
self.SetBestSize((28, height))
else:
self.SetBestSize((width, 28))
self.SetBounds(0, 0, wbound, hbound)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda evt: True)
def OnMouseEvents(self, event):
"""
Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`RulerCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if not self._indicators:
event.Skip()
return
mousePos = event.GetPosition()
if event.LeftDown():
self.CaptureMouse()
self.GetIndicator(mousePos)
self._mousePosition = mousePos
self.SetIndicatorValue(sendEvent=False)
elif event.Dragging() and self._currentIndicator:
self._mousePosition = mousePos
self.SetIndicatorValue()
elif event.LeftUp():
if self.HasCapture():
self.ReleaseMouse()
self.SetIndicatorValue(sendEvent=False)
if self._drawingparent:
self._drawingparent.Refresh()
self._currentIndicator = None
#else:
# self._currentIndicator = None
event.Skip()
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`RulerCtrl`.
:param `event`: a :class:`PaintEvent` event to be processed.
"""
dc = wx.BufferedPaintDC(self)
dc.SetBackground(wx.Brush(self._background))
dc.Clear()
self.Draw(dc)
def OnSize(self, event):
"""
Handles the ``wx.EVT_SIZE`` event for :class:`RulerCtrl`.
:param `event`: a :class:`SizeEvent` event to be processed.
"""
width, height = self.CheckStyle()
self.SetBounds(0, 0, width, height)
self.Invalidate()
event.Skip()
def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RulerCtrl`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This method is intentionally empty to reduce flicker.
"""
pass
def SetIndicatorValue(self, sendEvent=True):
"""
Sets the indicator value.
:param `sendEvent`: ``True`` to send a :class:`RulerCtrlEvent`, ``False`` otherwise.
"""
if self._currentIndicator is None:
return
left, top, right, bottom = self.GetBounds()
x = self._mousePosition.x
y = self._mousePosition.y
maxvalue = self._max
minvalue = self._min
if self._log:
minvalue = math.log10(minvalue)
maxvalue = math.log10(maxvalue)
deltarange = abs(self._max - self._min)
if self._orientation == wx.HORIZONTAL: # only x moves
value = deltarange*float(x)/(right - left)
else:
value = deltarange*float(y)/(bottom - top)
value += minvalue
if self._log:
value = 10**value
if value < self._min or value > self._max:
return
self.DrawOnParent(self._currentIndicator)
if sendEvent:
event = RulerCtrlEvent(wxEVT_INDICATOR_CHANGING, self._currentIndicator.GetId())
event.SetOldValue(self._currentIndicator.GetValue())
event.SetValue(value)
event.SetEventObject(self)
if self.GetEventHandler().ProcessEvent(event):
self.DrawOnParent(self._currentIndicator)
return
self._currentIndicator.SetValue(value)
if sendEvent:
event.SetEventType(wxEVT_INDICATOR_CHANGED)
event.SetOldValue(value)
self.GetEventHandler().ProcessEvent(event)
self.DrawOnParent(self._currentIndicator)
self.Refresh()
def GetIndicator(self, mousePos):
"""
Returns the indicator located at the mouse position `mousePos` (if any).
:param `mousePos`: the mouse position, an instance of :class:`Point`.
"""
for indicator in self._indicators:
if indicator.GetRect().Contains(mousePos):
self._currentIndicator = indicator
break
def CheckStyle(self):
""" Adjust the :class:`RulerCtrl` style accordingly to borders, units, etc..."""
width, height = self.GetSize()
if self._orientation & wx.HORIZONTAL:
if self._style & wx.NO_BORDER:
hbound = 28
wbound = width-1
elif self._style & wx.SIMPLE_BORDER:
hbound = 27
wbound = width-1
elif self._style & wx.STATIC_BORDER:
hbound = 26
wbound = width-3
elif self._style & wx.SUNKEN_BORDER:
hbound = 24
wbound = width-5
elif self._style & wx.RAISED_BORDER:
hbound = 22
wbound = width-7
elif self._style & wx.DOUBLE_BORDER:
hbound = 22
wbound = width-7
else:
if self._style & wx.NO_BORDER:
wbound = 28
hbound = height-1
elif self._style & wx.SIMPLE_BORDER:
wbound = 27
hbound = height-1
elif self._style & wx.STATIC_BORDER:
wbound = 26
hbound = height-3
elif self._style & wx.SUNKEN_BORDER:
wbound = 24
hbound = height-5
elif self._style & wx.RAISED_BORDER:
wbound = 22
hbound = height-7
elif self._style & wx.DOUBLE_BORDER:
wbound = 22
hbound = height-7
minText = self.LabelString(self._min, major=True)
maxText = self.LabelString(self._max, major=True)
dc = wx.ClientDC(self)
minWidth, minHeight = dc.GetTextExtent(minText)
maxWidth, maxHeight = dc.GetTextExtent(maxText)
maxWidth = max(maxWidth, minWidth)
maxHeight = max(maxHeight, minHeight)
if self._orientation == wx.HORIZONTAL:
if maxHeight + 4 > hbound:
hbound = maxHeight
self.SetBestSize((-1, maxHeight + 4))
if self.GetContainingSizer():
self.GetContainingSizer().Layout()
else:
if maxWidth + 4 > wbound:
wbound = maxWidth
self.SetBestSize((maxWidth + 4, -1))
if self.GetContainingSizer():
self.GetContainingSizer().Layout()
return wbound, hbound
def TickMajor(self, tick=True):
"""
Sets whether the major ticks should be ticked or not.
:param `tick`: ``True`` to show major ticks, ``False`` otherwise.
"""
if self._tickmajor != tick:
self._tickmajor = tick
self.Invalidate()
def TickMinor(self, tick=True):
"""
Sets whether the minor ticks should be ticked or not.
:param `tick`: ``True`` to show minor ticks, ``False`` otherwise.
"""
if self._tickminor != tick:
self._tickminor = tick
self.Invalidate()
def LabelMinor(self, label=True):
"""
Sets whether the minor ticks should be labeled or not.
:param `label`: ``True`` to label minor ticks, ``False`` otherwise.
"""
if self._labelminor != label:
self._labelminor = label
self.Invalidate()
def LabelMajor(self, label=True):
"""
Sets whether the major ticks should be labeled or not.
:param `label`: ``True`` to label major ticks, ``False`` otherwise.
"""
if self._labelmajor != label:
self._labelmajor = label
self.Invalidate()
def GetTimeFormat(self):
""" Returns the time format. """
return self._timeformat
def SetTimeFormat(self, format=TimeFormat):
"""
Sets the time format.
:param `format`: the format used to display time values.
"""
if self._timeformat != format:
self._timeformat = format
self.Invalidate()
def SetFormat(self, format):
"""
Sets the format for :class:`RulerCtrl`.
:param `format`: the format used to display values in :class:`RulerCtrl`. This can be
one of the following bits:
====================== ======= ==============================
Format Value Description
====================== ======= ==============================
``IntFormat`` 1 Integer format
``RealFormat`` 2 Real format
``TimeFormat`` 3 Time format
``LinearDBFormat`` 4 Linear DB format
``HHMMSS_Format`` 5 HHMMSS format
====================== ======= ==============================
"""
if self._format != format:
self._format = format
self.Invalidate()
def GetFormat(self):
"""
Returns the format used to display values in :class:`RulerCtrl`.
:see: :meth:`RulerCtrl.SetFormat` for a list of possible formats.
"""
return self._format
def SetLog(self, log=True):
"""
Sets whether :class:`RulerCtrl` should have a logarithmic scale or not.
:param `log`: ``True`` to use a logarithmic scake, ``False`` to use a
linear one.
"""
if self._log != log:
self._log = log
self.Invalidate()
def SetUnits(self, units):
"""
Sets the units that should be displayed beside the labels.
:param `units`: the units that should be displayed beside the labels.
"""
# Specify the name of the units (like "dB") if you
# want numbers like "1.6" formatted as "1.6 dB".
if self._units != units:
self._units = units
self.Invalidate()
def SetBackgroundColour(self, colour):
"""
Sets the :class:`RulerCtrl` background colour.
:param `colour`: an instance of :class:`Colour`.
:note: Overridden from :class:`PyPanel`.
"""
self._background = colour
wx.PyPanel.SetBackgroundColour(self, colour)
self.Refresh()
def SetOrientation(self, orient=None):
"""
Sets the :class:`RulerCtrl` orientation.
:param `orient`: can be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.
"""
if orient is None:
orient = wx.HORIZONTAL
if self._orientation != orient:
self._orientation = orient
if self._orientation == wx.VERTICAL and not self._hassetspacing:
self._spacing = 2
self.Invalidate()
def SetRange(self, minVal, maxVal):
"""
Sets the :class:`RulerCtrl` range.
:param `minVal`: the minimum value of :class:`RulerCtrl`;
:param `maxVal`: the maximum value of :class:`RulerCtrl`.
"""
# For a horizontal ruler,
# minVal is the value in the center of pixel "left",
# maxVal is the value in the center of pixel "right".
if self._min != minVal or self._max != maxVal:
self._min = minVal
self._max = maxVal
self.Invalidate()
def SetSpacing(self, spacing):
"""
Sets the :class:`RulerCtrl` spacing between labels.
:param `spacing`: the spacing between labels, in pixels.
"""
self._hassetspacing = True
if self._spacing != spacing:
self._spacing = spacing
self.Invalidate()
def SetLabelEdges(self, labelEdges=True):
"""
Sets whether the edge values should always be displayed or not.
:param `labelEdges`: ``True`` to always display edge labels, ``False`` otherwise/
"""
# If this is True, the edges of the ruler will always
# receive a label. If not, the nearest round number is
# labeled (which may or may not be the edge).
if self._labeledges != labelEdges:
self._labeledges = labelEdges
self.Invalidate()
def SetFlip(self, flip=True):
"""
Sets whether the orientation of the tick marks should be reversed.
:param `flip`: ``True`` to reverse the orientation of the tick marks, ``False``
otherwise.
"""
# If this is True, the orientation of the tick marks
# is reversed from the default eg. above the line
# instead of below
if self._flip != flip:
self._flip = flip
self.Invalidate()
for indicator in self._indicators:
indicator.RotateImage()
def SetFonts(self, minorFont, majorFont):
"""
Sets the fonts for minor and major tick labels.
:param `minorFont`: the font used to draw minor ticks, a valid :class:`Font` object;
:param `majorFont`: the font used to draw major ticks, a valid :class:`Font` object.
"""
self._minorfont = minorFont
self._majorfont = majorFont
if wx.Platform == "__WXMAC__":
self._minorfont.SetNoAntiAliasing(True)
self._majorfont.SetNoAntiAliasing(True)
self.Invalidate()
def SetTickPenColour(self, colour=wx.BLACK):
"""
Sets the pen colour to draw the ticks.
:param `colour`: a valid :class:`Colour` object.
"""
self._tickpen = wx.Pen(colour)
self.Refresh()
def SetLabelColour(self, colour=wx.BLACK):
"""
Sets the labels colour.
:param `colour`: a valid :class:`Colour` object.
"""
self._textcolour = colour
self.Refresh()
def OfflimitsPixels(self, start, end):
""" Used internally. """
if not self._userbits:
if self._orientation == wx.HORIZONTAL:
self._length = self._right-self._left
else:
self._length = self._bottom-self._top
self._userbits = [0]*self._length
self._userbitlen = self._length+1
if end < start:
i = end
end = start
start = i
if start < 0:
start = 0
if end > self._length:
end = self._length
for ii in xrange(start, end+1):
self._userbits[ii] = 1
def SetBounds(self, left, top, right, bottom):
"""
Sets the bounds for :class:`RulerCtrl` (its client rectangle).
:param `left`: the left corner of the client rectangle;
:param `top`: the top corner of the client rectangle;
:param `right`: the right corner of the client rectangle;
:param `bottom`: the bottom corner of the client rectangle.
"""
if self._left != left or self._top != top or self._right != right or \
self._bottom != bottom:
self._left = left
self._top = top
self._right = right
self._bottom = bottom
self.Invalidate()
def GetBounds(self):
""" Returns the :class:`RulerCtrl` bounds (its client rectangle). """
return self._left, self._top, self._right, self._bottom
def AddIndicator(self, id, value):
"""
Adds an indicator to :class:`RulerCtrl`. You should pass a unique `id` and a starting
`value` for the indicator.
:param `id`: the indicator identifier;
:param `value`: the indicator initial value.
"""
self._indicators.append(Indicator(self, id, value))
self.Refresh()
def SetIndicatorColour(self, id, colour=None):
"""
Sets the indicator colour.
:param `id`: the indicator identifier;
:param `colour`: a valid :class:`Colour` object.
:note: This method requires PIL to change the image palette.
"""
if not _hasPIL:
return
if colour is None:
colour = wx.WHITE
for indicator in self._indicators:
if indicator.GetId() == id:
indicator.SetColour(colour)
break
def Invalidate(self):
""" Invalidates the ticks calculations. """
self._valid = False
if self._orientation == wx.HORIZONTAL:
self._length = self._right - self._left
else:
self._length = self._bottom - self._top
self._majorlabels = []
self._minorlabels = []
self._bits = []
self._userbits = []
self._userbitlen = 0
self.Refresh()
def FindLinearTickSizes(self, UPP):
""" Used internally. """
# Given the dimensions of the ruler, the range of values it
# has to display, and the format (i.e. Int, Real, Time),
# figure out how many units are in one Minor tick, and
# in one Major tick.
#
# The goal is to always put tick marks on nice round numbers
# that are easy for humans to grok. This is the most tricky
# with time.
# As a heuristic, we want at least 16 pixels
# between each minor tick
units = 16.0*abs(UPP)
self._digits = 0
if self._format == LinearDBFormat:
if units < 0.1:
self._minor = 0.1
self._major = 0.5
return
if units < 1.0:
self._minor = 1.0
self._major = 6.0
return
self._minor = 3.0
self._major = 12.0
return
elif self._format == IntFormat:
d = 1.0
while 1:
if units < d:
self._minor = d
self._major = d*5.0
return
d = d*5.0
if units < d:
self._minor = d
self._major = d*2.0
return
d = 2.0*d
elif self._format == TimeFormat:
if units > 0.5:
if units < 1.0: # 1 sec
self._minor = 1.0
self._major = 5.0
return
if units < 5.0: # 5 sec
self._minor = 5.0
self._major = 15.0
return
if units < 10.0:
self._minor = 10.0
self._major = 30.0
return
if units < 15.0:
self._minor = 15.0
self._major = 60.0
return
if units < 30.0:
self._minor = 30.0
self._major = 60.0
return
if units < 60.0: # 1 min
self._minor = 60.0
self._major = 300.0
return
if units < 300.0: # 5 min
self._minor = 300.0
self._major = 900.0
return
if units < 600.0: # 10 min
self._minor = 600.0
self._major = 1800.0
return
if units < 900.0: # 15 min
self._minor = 900.0
self._major = 3600.0
return
if units < 1800.0: # 30 min
self._minor = 1800.0
self._major = 3600.0
return
if units < 3600.0: # 1 hr
self._minor = 3600.0
self._major = 6*3600.0
return
if units < 6*3600.0: # 6 hrs
self._minor = 6*3600.0
self._major = 24*3600.0
return
if units < 24*3600.0: # 1 day
self._minor = 24*3600.0
self._major = 7*24*3600.0
return
self._minor = 24.0*7.0*3600.0 # 1 week
self._major = 24.0*7.0*3600.0
# Otherwise fall through to RealFormat
# (fractions of a second should be dealt with
# the same way as for RealFormat)
elif self._format == RealFormat:
d = 0.000001
self._digits = 6
while 1:
if units < d:
self._minor = d
self._major = d*5.0
return
d = d*5.0
if units < d:
self._minor = d
self._major = d*2.0
return
d = d*2.0
self._digits = self._digits - 1
def LabelString(self, d, major=None):
""" Used internally. """
# Given a value, turn it into a string according
# to the current ruler format. The number of digits of
# accuracy depends on the resolution of the ruler,
# i.e. how far zoomed in or out you are.
s = ""
if d < 0.0 and d + self._minor > 0.0:
d = 0.0
if self._format == IntFormat:
s = "%d"%int(math.floor(d+0.5))
elif self._format == LinearDBFormat:
if self._minor >= 1.0:
s = "%d"%int(math.floor(d+0.5))
else:
s = "%0.1f"%d
elif self._format == RealFormat:
if self._minor >= 1.0:
s = "%d"%int(math.floor(d+0.5))
else:
s = (("%." + str(self._digits) + "f")%d).strip()
elif self._format == TimeFormat:
if major:
if d < 0:
s = "-"
d = -d
if self.GetTimeFormat() == HHMMSS_Format:
secs = int(d + 0.5)
if self._minor >= 1.0:
s = ("%d:%02d:%02d")%(secs/3600, (secs/60)%60, secs%60)
else:
t1 = ("%d:%02d:")%(secs/3600, (secs/60)%60)
format = "%" + "%0d.%dlf"%(self._digits+3, self._digits)
t2 = format%(d%60.0)
s = s + t1 + t2
else:
if self._minor >= 3600.0:
hrs = int(d/3600.0 + 0.5)
h = "%d:00:00"%hrs
s = s + h
elif self._minor >= 60.0:
minutes = int(d/60.0 + 0.5)
if minutes >= 60:
m = "%d:%02d:00"%(minutes/60, minutes%60)
else:
m = "%d:00"%minutes
s = s + m
elif self._minor >= 1.0:
secs = int(d + 0.5)
if secs >= 3600:
t = "%d:%02d:%02d"%(secs/3600, (secs/60)%60, secs%60)
elif secs >= 60:
t = "%d:%02d"%(secs/60, secs%60)
else:
t = "%d"%secs
s = s + t
else:
secs = int(d)
if secs >= 3600:
t1 = "%d:%02d:"%(secs/3600, (secs/60)%60)
elif secs >= 60:
t1 = "%d:"%(secs/60)
if secs >= 60:
format = "%%0%d.%dlf"%(self._digits+3, self._digits)
else:
format = "%%%d.%dlf"%(self._digits+3, self._digits)
t2 = format%(d%60.0)
s = s + t1 + t2
if self._units != "":
s = s + " " + self._units
return s
def Tick(self, dc, pos, d, major):
"""
Ticks a particular position.
:param `dc`: an instance of :class:`DC`;
:param `pos`: the label position;
:param `d`: the current label value;
:param `major`: ``True`` if it is a major ticks, ``False`` if it is a minor one.
"""
if major:
label = Label()
self._majorlabels.append(label)
else:
label = Label()
self._minorlabels.append(label)
label.pos = pos
label.lx = self._left - 2000 # don't display
label.ly = self._top - 2000 # don't display
label.text = ""
dc.SetFont((major and [self._majorfont] or [self._minorfont])[0])
l = self.LabelString(d, major)
strw, strh = dc.GetTextExtent(l)
if self._orientation == wx.HORIZONTAL:
strlen = strw
strpos = pos - strw/2
if strpos < 0:
strpos = 0
if strpos + strw >= self._length:
strpos = self._length - strw
strleft = self._left + strpos
if self._flip:
strtop = self._top + 4
self._maxheight = max(self._maxheight, 4 + strh)
else:
strtop = self._bottom - strh - 6
self._maxheight = max(self._maxheight, strh + 6)
else:
strlen = strh
strpos = pos - strh/2
if strpos < 0:
strpos = 0
if strpos + strh >= self._length:
strpos = self._length - strh
strtop = self._top + strpos
if self._flip:
strleft = self._left + 5
self._maxwidth = max(self._maxwidth, 5 + strw)
else:
strleft = self._right - strw - 6
self._maxwidth = max(self._maxwidth, strw + 6)
# See if any of the pixels we need to draw this
# label is already covered
if major and self._labelmajor or not major and self._labelminor:
for ii in xrange(strlen):
if self._bits[strpos+ii]:
return
# If not, position the label and give it text
label.lx = strleft
label.ly = strtop
label.text = l
if major:
if self._tickmajor and not self._labelmajor:
label.text = ""
self._majorlabels[-1] = label
else:
if self._tickminor and not self._labelminor:
label.text = ""
label.text = label.text.replace(self._units, "")
self._minorlabels[-1] = label
# And mark these pixels, plus some surrounding
# ones (the spacing between labels), as covered
if (not major and self._labelminor) or (major and self._labelmajor):
leftmargin = self._spacing
if strpos < leftmargin:
leftmargin = strpos
strpos = strpos - leftmargin
strlen = strlen + leftmargin
rightmargin = self._spacing
if strpos + strlen > self._length - self._spacing:
rightmargin = self._length - strpos - strlen
strlen = strlen + rightmargin
for ii in xrange(strlen):
self._bits[strpos+ii] = 1
def Update(self, dc):
"""
Updates all the ticks calculations.
:param `dc`: an instance of :class:`DC`.
"""
# This gets called when something has been changed
# (i.e. we've been invalidated). Recompute all
# tick positions.
if self._orientation == wx.HORIZONTAL:
self._maxwidth = self._length
self._maxheight = 0
else:
self._maxwidth = 0
self._maxheight = self._length
self._bits = [0]*(self._length+1)
self._middlepos = []
if self._userbits:
for ii in xrange(self._length):
self._bits[ii] = self._userbits[ii]
else:
for ii in xrange(self._length):
self._bits[ii] = 0
if not self._log:
UPP = (self._max - self._min)/float(self._length) # Units per pixel
self.FindLinearTickSizes(UPP)
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
# Zero (if it's in the middle somewhere)
if self._min*self._max < 0.0:
mid = int(self._length*(self._min/(self._min-self._max)) + 0.5)
self.Tick(dc, mid, 0.0, True)
sg = ((UPP > 0.0) and [1.0] or [-1.0])[0]
# Major ticks
d = self._min - UPP/2
lastd = d
majorint = int(math.floor(sg*d/self._major))
ii = -1
while ii <= self._length:
ii = ii + 1
lastd = d
d = d + UPP
if int(math.floor(sg*d/self._major)) > majorint:
majorint = int(math.floor(sg*d/self._major))
self.Tick(dc, ii, sg*majorint*self._major, True)
# Minor ticks
d = self._min - UPP/2
lastd = d
minorint = int(math.floor(sg*d/self._minor))
ii = -1
while ii <= self._length:
ii = ii + 1
lastd = d
d = d + UPP
if int(math.floor(sg*d/self._minor)) > minorint:
minorint = int(math.floor(sg*d/self._minor))
self.Tick(dc, ii, sg*minorint*self._minor, False)
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
else:
# log case
lolog = math.log10(self._min)
hilog = math.log10(self._max)
scale = self._length/(hilog - lolog)
lodecade = int(math.floor(lolog))
hidecade = int(math.ceil(hilog))
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
startdecade = 10.0**lodecade
# Major ticks are the decades
decade = startdecade
for ii in xrange(lodecade, hidecade):
if ii != lodecade:
val = decade
if val > self._min and val < self._max:
pos = int(((math.log10(val) - lolog)*scale)+0.5)
self.Tick(dc, pos, val, True)
decade = decade*10.0
# Minor ticks are multiples of decades
decade = startdecade
for ii in xrange(lodecade, hidecade):
for jj in xrange(2, 10):
val = decade*jj
if val >= self._min and val < self._max:
pos = int(((math.log10(val) - lolog)*scale)+0.5)
self.Tick(dc, pos, val, False)
decade = decade*10.0
self._valid = True
def Draw(self, dc):
"""
Actually draws the whole :class:`RulerCtrl`.
:param `dc`: an instance of :class:`DC`.
"""
if not self._valid:
self.Update(dc)
dc.SetBrush(wx.Brush(self._background))
dc.SetPen(self._tickpen)
dc.SetTextForeground(self._textcolour)
dc.DrawRectangleRect(self.GetClientRect())
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left, self._top, self._right+1, self._top)
else:
dc.DrawLine(self._left, self._bottom-1, self._right+1, self._bottom-1)
else:
if self._flip:
dc.DrawLine(self._left, self._top, self._left, self._bottom+1)
else:
dc.DrawLine(self._right-1, self._top, self._right-1, self._bottom+1)
dc.SetFont(self._majorfont)
for label in self._majorlabels:
pos = label.pos
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left + pos, self._top,
self._left + pos, self._top + 5)
else:
dc.DrawLine(self._left + pos, self._bottom - 5,
self._left + pos, self._bottom)
else:
if self._flip:
dc.DrawLine(self._left, self._top + pos,
self._left + 5, self._top + pos)
else:
dc.DrawLine(self._right - 5, self._top + pos,
self._right, self._top + pos)
if label.text != "":
dc.DrawText(label.text, label.lx, label.ly)
dc.SetFont(self._minorfont)
for label in self._minorlabels:
pos = label.pos
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left + pos, self._top,
self._left + pos, self._top + 3)
else:
dc.DrawLine(self._left + pos, self._bottom - 3,
self._left + pos, self._bottom)
else:
if self._flip:
dc.DrawLine(self._left, self._top + pos,
self._left + 3, self._top + pos)
else:
dc.DrawLine(self._right - 3, self._top + pos,
self._right, self._top + pos)
if label.text != "":
dc.DrawText(label.text, label.lx, label.ly)
for indicator in self._indicators:
indicator.Draw(dc)
def SetDrawingParent(self, dparent):
"""
Sets the window to which :class:`RulerCtrl` draws a thin line over.
:param `dparent`: an instance of :class:`Window`, representing the window to
which :class:`RulerCtrl` draws a thin line over.
"""
self._drawingparent = dparent
def GetDrawingParent(self):
""" Returns the window to which :class:`RulerCtrl` draws a thin line over. """
return self._drawingparent
def DrawOnParent(self, indicator):
"""
Actually draws the thin line over the drawing parent window.
:param `indicator`: the current indicator, an instance of :class:`Indicator`.
:note: This method is currently not available on wxMac as it uses :class:`ScreenDC`.
"""
if not self._drawingparent:
return
xpos, ypos = indicator.GetPosition()
parentrect = self._drawingparent.GetClientRect()
dc = wx.ScreenDC()
dc.SetLogicalFunction(wx.INVERT)
dc.SetPen(self._drawingpen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
imgx, imgy = indicator.GetImageSize()
if self._orientation == wx.HORIZONTAL:
x1 = xpos+ imgx/2
y1 = parentrect.y
x2 = x1
y2 = parentrect.height
x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)
elif self._orientation == wx.VERTICAL:
x1 = parentrect.x
y1 = ypos + imgy/2
x2 = parentrect.width
y2 = y1
x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)
dc.DrawLine(x1, y1, x2, y2)
dc.SetLogicalFunction(wx.COPY)
|
ktan2020/legacy-automation
|
win/Lib/site-packages/wx-3.0-msw/wx/lib/agw/rulerctrl.py
|
Python
|
mit
| 57,819
|
from __future__ import absolute_import
from __future__ import division
from builtins import object
from past.utils import old_div
from proteus import *
from proteus.default_p import *
import os
try:
from .parameters_for_poisson import *
except:
from parameters_for_poisson import *
name = "poisson"
assert ct.nd==2 or ct.nd==3, "Choose nd=2, or 3"
nd = ct.nd
initialConditions = None
##########
# DOMAIN #
##########
nn=(2**ct.refinement)*10+1
he=old_div(1.0,(nn-1.0))
if (nd==2):
box=Domain.RectangularDomain(L=(1.0,1.0),
x=(0.0,0.0),
name="box");
else:
nn=5
he=old_div(1.0,(nn-1.0))
box=Domain.RectangularDomain(L=(1.0,1.0,1.0),
x=(0.0,0.0,0.0),
name="box");
genMesh=ct.genMesh #False
if(genMesh):
box.writePoly("box")
if ct.unstructured:
assert ct.useHex==False, "set useHex=False for unstructure meshes"
domain=Domain.PlanarStraightLineGraphDomain(fileprefix="box")
domain.boundaryTags = box.boundaryTags
bt = domain.boundaryTags
triangleOptions="pAq30Dena%8.8f" % (0.5*he**2,)
else:
domain = box
domain.MeshOptions.nn = domain.MeshOptions.nnx = domain.MeshOptions.nny = domain.MeshOptions.nnz = nn
#the initial test uses triangleFlag=0 from defaults
domain.MeshOptions.triangleFlag=0
nc = 1
##################
# EXACT SOLUTION #
##################
class exact_soln(object):
def __init__(self):
pass
def uOfXT(self,x,t):
if (nd==2):
return np.sin(2*pi*x[0])*np.sin(2*pi*x[1])
else:
return np.sin(2*pi*x[0])*np.sin(2*pi*x[1])*np.sin(2*pi*x[2])
def duOfXT(self,x,t):
if (nd==2):
return [2*pi*np.cos(2*pi*x[0])*np.sin(2*pi*x[1]),
2*pi*np.sin(2*pi*x[0])*np.cos(2*pi*x[1])]
else:
return [2*pi*np.cos(2*pi*x[0])*np.sin(2*pi*x[1])*np.sin(2*pi*x[2]),
2*pi*np.sin(2*pi*x[0])*np.cos(2*pi*x[1])*np.sin(2*pi*x[2]),
2*pi*np.sin(2*pi*x[0])*np.sin(2*pi*x[1])*np.cos(2*pi*x[2])]
analyticalSolution = {0:exact_soln()}
#########################
# DIFFUSION COEFFICIENT #
#########################
def A(x):
if (nd==2):
return numpy.array([[1.0,0.0],[0.0,1.0]],'d')
else:
return numpy.array([[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],'d')
aOfX = {0:A}
##############
# FORCE TERM #
##############
def f(x):
if (nd==2):
return 8*pi**2*np.sin(2*pi*x[0])*np.sin(2*pi*x[1])
else:
return 12*pi**2*np.sin(2*pi*x[0])*np.sin(2*pi*x[1])*np.sin(2*pi*x[2])
fOfX = {0:f}
#######################
# BOUNDARY CONDITIONS #
#######################
def getDBC(x,flag):
if (nd==2):
if x[0] in [0.0,1.0] or x[1] in [0.0,1.0]:
return lambda x,t: 0.
else:
if x[0] in [0.0,1.0] or x[1] in [0.0,1.0] or x[2] in [0.0,1.0]:
return lambda x,t: 0.
dirichletConditions = {0:getDBC}
coefficients = TransportCoefficients.PoissonEquationCoefficients({0:A},{0:f},nc,nd,l2proj=[False])
class LevelModelType(OneLevelTransport):
def getResidual(self,u,r):
OneLevelTransport.getResidual(self,u,r)
def calculateElementResidual(self):
OneLevelTransport.calculateElementResidual(self)
|
erdc/proteus
|
proteus/tests/BernsteinPolynomials/poisson_eqn/poisson_p.py
|
Python
|
mit
| 3,313
|
# Generated by Django 3.0.7 on 2020-09-27 13:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('edegal', '0025_photographer_flickr_handle'),
]
operations = [
migrations.CreateModel(
name='LarppikuvatPhotographerProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contact', models.TextField(blank=True)),
('hours', models.TextField(blank=True)),
('delivery_schedule', models.TextField(blank=True)),
('delivery_practice', models.TextField(blank=True)),
('delivery_method', models.TextField(blank=True)),
('copy_protection', models.TextField(blank=True)),
('expected_compensation', models.TextField(blank=True)),
('photographer', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='larppikuvat_profile', to='edegal.Photographer')),
],
),
]
|
conikuvat/edegal
|
backend/larppikuvat/migrations/0001_initial.py
|
Python
|
mit
| 1,162
|
# -*- coding: utf-8 -*-
import pickle
import sqlite3
import threading
from abc import ABCMeta, abstractmethod
from collections import namedtuple
InternalEvent = namedtuple(
'InternalEvent',
('identifier', 'state_change_id', 'block_number', 'event_object'),
)
# TODO:
# - snapshots should be used to reduce the log file size
class StateChangeLogSerializer(object):
""" StateChangeLogSerializer
An abstract class defining the serialization interface for the
Transaction log. Allows for pluggable serializer backends.
"""
__metaclass__ = ABCMeta
@abstractmethod
def serialize(self, transaction):
pass
@abstractmethod
def deserialize(self, data):
pass
class PickleTransactionSerializer(StateChangeLogSerializer):
""" PickleTransactionSerializer
A simple transaction serializer using pickle
"""
def serialize(self, transaction):
# Some of our StateChange classes have __slots__ without having a __getstate__
# As seen in the SO question below:
# http://stackoverflow.com/questions/2204155/why-am-i-getting-an-error-about-my-class-defining-slots-when-trying-to-pickl#2204702
# We can either add a __getstate__ to all of them or use the `-1` protocol and be
# incompatible with ancient python version. Here I opt for the latter.
return pickle.dumps(transaction, -1)
def deserialize(self, data):
return pickle.loads(data)
class StateChangeLogStorageBackend(object):
""" StateChangeLogStorageBackend
An abstract class defining the storage backend for the transaction log.
Allows for pluggable storage backends.
"""
__metaclass__ = ABCMeta
@abstractmethod
def write_state_change(self, data):
pass
@abstractmethod
def write_state_snapshot(self, statechange_id, data):
pass
@abstractmethod
def read(self):
pass
class StateChangeLogSQLiteBackend(StateChangeLogStorageBackend):
def __init__(self, database_path):
self.conn = sqlite3.connect(database_path)
self.conn.text_factory = str
self.conn.execute("PRAGMA foreign_keys=ON")
cursor = self.conn.cursor()
cursor.execute(
'CREATE TABLE IF NOT EXISTS state_changes ('
' id integer primary key autoincrement, data binary'
')'
)
cursor.execute(
'CREATE TABLE IF NOT EXISTS state_snapshot ('
'identifier integer primary key, statechange_id integer, data binary, '
'FOREIGN KEY(statechange_id) REFERENCES state_changes(id)'
')'
)
cursor.execute(
'CREATE TABLE IF NOT EXISTS state_events ('
'identifier integer primary key, source_statechange_id integer NOT NULL, '
'block_number integer NOT NULL, data binary, '
'FOREIGN KEY(source_statechange_id) REFERENCES state_changes(id)'
')'
)
self.conn.commit()
self.sanity_check()
# When writting to a table where the primary key is the identifier and we want
# to return said identifier we use cursor.lastrowid, which uses sqlite's last_insert_rowid
# https://github.com/python/cpython/blob/2.7/Modules/_sqlite/cursor.c#L727-L732
#
# According to the documentation (http://www.sqlite.org/c3ref/last_insert_rowid.html)
# if a different thread tries to use the same connection to write into the table
# while we query the last_insert_rowid, the result is unpredictable. For that reason
# we have this write lock here.
#
# TODO (If possible):
# Improve on this and find a better way to protect against this potential race
# condition.
self.write_lock = threading.Lock()
def sanity_check(self):
""" Ensures that NUL character can be safely inserted and recovered
from the database.
http://bugs.python.org/issue13676
"""
data = '\x00a'
self.conn.execute(
'INSERT INTO state_changes (id, data) VALUES (null,?)',
(data, ),
)
result = next(self.conn.execute('SELECT data FROM state_changes ORDER BY id DESC'))
if result[0] != data:
raise RuntimeError(
'Database cannot save NUL character, ensure python is at least 2.7.3'
)
self.conn.rollback()
def write_state_change(self, data):
with self.write_lock:
cursor = self.conn.cursor()
cursor.execute(
'INSERT INTO state_changes(id, data) VALUES(null,?)',
(data,)
)
last_id = cursor.lastrowid
self.conn.commit()
return last_id
def write_state_snapshot(self, statechange_id, data):
# TODO: Snapshotting is not yet implemented. This is just skeleton code
# Issue: https://github.com/raiden-network/raiden/issues/593
# This skeleton code assumes we only keep a single snapshot and overwrite it each time.
with self.write_lock:
cursor = self.conn.cursor()
cursor.execute(
'INSERT OR REPLACE INTO state_snapshot('
'identifier, statechange_id, data) VALUES(?,?,?)',
(1, statechange_id, data)
)
last_id = cursor.lastrowid
self.conn.commit()
return last_id
def write_state_events(self, statechange_id, events_data):
"""Do an 'execute_many' write of state events. `events_data` should be a
list of tuples of the form:
(None, source_statechange_id, block_number, serialized_event_data)
"""
cursor = self.conn.cursor()
cursor.executemany(
'INSERT INTO state_events('
'identifier, source_statechange_id, block_number, data) VALUES(?,?,?,?)',
events_data
)
self.conn.commit()
def get_state_snapshot(self):
""" Return the last state snapshot as a tuple of (state_change_id, data)"""
cursor = self.conn.cursor()
result = cursor.execute('SELECT * from state_snapshot')
result = result.fetchall()
if result == list():
return None
assert len(result) == 1
return (result[0][1], result[0][2])
def get_state_change_by_id(self, identifier):
cursor = self.conn.cursor()
result = cursor.execute(
'SELECT data from state_changes where id=?', (identifier,)
)
result = result.fetchall()
if result != list():
assert len(result) == 1
result = result[0][0]
return result
def get_events_in_range(self, from_block, to_block):
cursor = self.conn.cursor()
if from_block is None:
from_block = 0
if to_block is None:
result = cursor.execute(
'SELECT * from state_events WHERE block_number >= ?',
(from_block,)
)
else:
result = cursor.execute(
'SELECT * from state_events WHERE block_number '
'BETWEEN ? AND ?', (from_block, to_block)
)
result = result.fetchall()
return result
def read(self):
pass
def __del__(self):
self.conn.close()
class StateChangeLog(object):
def __init__(
self,
storage_instance,
serializer_instance=PickleTransactionSerializer()):
if not isinstance(serializer_instance, StateChangeLogSerializer):
raise ValueError(
'serializer_instance must follow the StateChangeLogSerializer interface'
)
self.serializer = serializer_instance
if not isinstance(storage_instance, StateChangeLogStorageBackend):
raise ValueError(
'storage_instance must follow the StateChangeLogStorageBackend interface'
)
self.storage = storage_instance
def log(self, state_change):
""" Log a state change and return its identifier"""
# TODO: Issue 587
# Implement a queue of state changes for batch writting
serialized_data = self.serializer.serialize(state_change)
return self.storage.write_state_change(serialized_data)
def log_events(self, state_change_id, events, current_block_number):
""" Log the events that were generated by `state_change_id` into the write ahead Log
"""
assert isinstance(events, list)
self.storage.write_state_events(
state_change_id,
[(None, state_change_id, current_block_number, self.serializer.serialize(event))
for event in events]
)
def get_events_in_block_range(self, from_block, to_block):
"""Get the raiden events in the period (inclusive) ranging from
`from_block` to `to_block`.
This function returns a list of tuples of the form:
(identifier, generated_statechange_id, block_number, event_object)
"""
results = self.storage.get_events_in_range(from_block, to_block)
return [
InternalEvent(res[0], res[1], res[2], self.serializer.deserialize(res[3]))
for res in results
]
def get_state_change_by_id(self, identifier):
serialized_data = self.storage.get_state_change_by_id(identifier)
return self.serializer.deserialize(serialized_data)
def snapshot(self, state_change_id, state):
serialized_data = self.serializer.serialize(state)
self.storage.write_state_snapshot(state_change_id, serialized_data)
|
tomashaber/raiden
|
raiden/transfer/log.py
|
Python
|
mit
| 9,715
|
import contextlib
from uuss.server import model
from lolapps.common import uums
from lolapps.util import json
import os
import simplejson
import struct
import time
try:
# Try importing the C++ extension version
import uuss_pb
except:
# The dynamic python version will automatically be used
pass
from uuss.uuss_pb2 import *
from uuss.server import model
from lolapps.common import uums
from lolapps.util.adapters import chunking
from lolapps.util import lolsocket
import logging
log = logging.getLogger(__name__)
class UUSSProtocolException(Exception):
pass
class UUSSShardDownException(UUSSProtocolException):
pass
class UUSSFailHealthcheckException(UUSSProtocolException):
pass
class UUSSAction(object):
"""
Base class for UUSS actions.
Note: the get_response and _call methods are set as @contextlib.contextmanager
in order for a get-with-lock to be able to use the with userstate.open mechanism
to ensure that the lock is released at the appropriate time.
"""
def __init__(self):
self.Request = None
self.Response = None
@contextlib.contextmanager
def get_response(self, protocol, req, config):
log.debug("UUSSAction.get_response start (%r, %r)", req.user_id, req.game)
userstate = getattr(model, req.game).userstate
log.debug("UUSSAction.get_response userstate: %r", userstate)
with self._call(protocol, userstate, req, config) as resp:
assert req.user_id == resp.user_id
assert req.game == resp.game
log.debug("UUSSAction.get_response pre-yield (%r, %r)", req.user_id, req.game)
yield resp
log.debug("UUSSAction.get_response post-yield (%r, %r)", req.user_id, req.game)
log.debug("UUSSAction.get_response end (%r, %r)", req.user_id, req.game)
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
raise Exception('Implement me!')
## UUSS (UserState) Protocol ##
class Get(UUSSAction):
def __init__(self):
self.Request = GetRequest
self.Response = GetResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("Get._call start (%r, %r)", req.user_id, req.game)
if req.lock:
# If a lock is requested we need to keep control within this 'with' block
# until we receive a ReleaseLock message but we also need to "return"
# the userstate requested. This is why this method and UUSSAction.get_response
# are contextmanagers. 'yield' allows us to return the value without
# leaving the 'with' block.
with userstate.open(
req.user_id,
create_if_missing=req.create_if_missing,
lock_timeout=req.lock_timeout,
max_wait=req.lock_max_wait,
label=req.lock_label,
raw=True
) as (state, chunked):
log.debug("Get._call pre-yield (%r, %r)", req.user_id, req.game)
yield self._build_response(state, chunked, req.game, req.user_id)
log.debug("Get._call post-yield (%r, %r)", req.user_id, req.game)
# we require a ReleaseLock message before we can leave this context and release the lock
self._wait_for_release_lock(protocol, req, config)
else:
(state, chunked) = userstate.get(req.user_id, req.create_if_missing, raw=True)
log.debug("Get._call pre-yield (%r, %r)", req.user_id, req.game)
yield self._build_response(state, chunked, req.game, req.user_id)
log.debug("Get._call post-yield (%r, %r)", req.user_id, req.game)
log.debug("Get._call end (%r, %r)", req.user_id, req.game)
def _wait_for_release_lock(self, protocol, get_req, config):
"""
Same as the normal server loop except that we will break once we get and process a ReleaseLock message.
@see server.connection.ConnectionHandler.run
"""
log.debug("Get._wait_for_release_lock start (%r, %r)", get_req.user_id, get_req.game)
while True:
log.debug("Get._wait_for_release_lock loop (%r, %r)", get_req.user_id, get_req.game)
(version, req) = protocol.recv_message()
if req.__class__ is ReleaseLock:
if req.game != get_req.game:
raise UUSSProtocolException("ReleaseLock.game (%r) != GetRequest.game (%r)" % (req.game, get_req.game))
if req.user_id != get_req.user_id:
raise UUSSProtocolException("ReleaseLock.user_id (%r) != GetRequest.user_id (%r)" % (req.user_id, get_req.user_id))
with get_processor_for_message(req, version).get_response(protocol, req, config) as resp:
protocol.send_message(resp, version)
if req.__class__ is ReleaseLock:
log.debug("Get._wait_for_release_lock end (%r, %r)", get_req.user_id, req.game)
return
def _build_response(self, state, chunked, game, user_id):
if not chunked:
# get the state in a chunked format for sending along the wire
# there will be only a master chunk with no chunk config specified
state = chunking.blow_chunks(state)
resp = self.Response()
resp.game = game
resp.user_id = user_id
if state is None:
resp.state = ""
else:
resp.state = state
return resp
class Save(UUSSAction):
def __init__(self):
self.Request = SaveRequest
self.Response = SaveResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("Save._call start (%r, %r)", req.user_id, req.game)
userstate.save(req.user_id, req.state)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
yield resp
log.debug("Save._call end (%r, %r)", req.user_id, req.game)
class Lock(UUSSAction):
def __init__(self):
self.Request = ReleaseLock
self.Response = LockReleased
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("Lock._call start (%r, %r)", req.user_id, req.game)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
log.debug("Lock._call pre-yield (%r, %r)", req.user_id, req.game)
yield resp
log.debug("Lock._call post-yield (%r, %r)", req.user_id, req.game)
log.debug("Lock._call end (%r, %r)", req.user_id, req.game)
class Delete(UUSSAction):
def __init__(self):
self.Request = DeleteRequest
self.Response = DeleteResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
if userstate.is_remote:
raise UUSSProtocolException(
"DeleteRequest sent for user_id %r game %r but that game is remote. I will only delete userstates in my local games."
% (req.user_id, req.game))
with userstate.open(req.user_id, label='UUSS.Delete') as state:
log.warn("[w:delete_userstate] Deleting userstate for user_id %r game %r, state follows\n%s", req.user_id, req.game, json.dumps(state))
userstate.delete(req.user_id)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
yield resp
## UUMS protocol ##
class GetMessages(UUSSAction):
def __init__(self):
self.Request = GetMessagesRequest
self.Response = GetMessagesResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("GetMessages._call start (%r, %r)", req.user_id, req.game)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
resp.messages.extend([ simplejson.dumps(m) for m in userstate.get_messages(req.user_id) ])
log.debug("GetMessages._call pre-yield (%r, %r)", req.user_id, req.game)
yield resp
log.debug("GetMessages._call post-yield (%r, %r)", req.user_id, req.game)
log.debug("GetMessages._call end (%r, %r)", req.user_id, req.game)
class SendMessage(UUSSAction):
def __init__(self):
self.Request = SendMessageRequest
self.Response = SendMessageResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("SendMessage._call start (%r, %r)", req.user_id, req.game)
if config.get('uums.send_message_type', 'direct') == 'mq':
log.debug("Using mq")
if not req.message_id:
req.message_id = uums.new_message_id()
msg_id = req.message_id
model.mq.send(model.MQ_UUSS, ''.join(UUSSProtocol._encode_message(req)))
else:
send_message = userstate.send_message if hasattr(userstate, 'send_message') else userstate.send_message_from
msg_id = send_message(
req.source_game,
req.source_user_id,
req.user_id,
simplejson.loads(req.message),
req.priority)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
resp.message_id = msg_id
log.debug("SendMessage._call pre-yield (%r, %r)", req.user_id, req.game)
yield resp
log.debug("SendMessage._call post-yield (%r, %r)", req.user_id, req.game)
log.debug("SendMessage._call end (%r, %r)", req.user_id, req.game)
class RemoveMessages(UUSSAction):
def __init__(self):
self.Request = RemoveMessagesRequest
self.Response = RemoveMessagesResponse
@contextlib.contextmanager
def _call(self, protocol, userstate, req, config):
log.debug("RemoveMessages._call start (%r, %r)", req.user_id, req.game)
userstate.remove_messages(req.user_id, req.message_ids)
resp = self.Response()
resp.game = req.game
resp.user_id = req.user_id
log.debug("RemoveMessages._call pre-yield (%r, %r)", req.user_id, req.game)
yield resp
log.debug("RemoveMessages._call post-yield (%r, %r)", req.user_id, req.game)
log.debug("RemoveMessages._call end (%r, %r)", req.user_id, req.game)
## Ping!
class PingPong(UUSSAction):
def __init__(self):
self.Request = Ping
self.Response = Pong
@contextlib.contextmanager
def get_response(self, protocol, req, config):
log.debug("Ping._call start (%r)", req.counter)
resp = self.Response()
resp.counter = req.counter
log.debug("Ping._call pre-yield (%r)", req.counter)
if protocol.fail_healthcheck:
raise UUSSFailHealthcheckException("Failing healthcheck")
yield resp
log.debug("Ping._call post-yield (%r)", req.counter)
log.debug("Ping._call end (%r)", req.counter)
MSG_PROCESSORS = {
3: [
Get(),
Save(),
Lock(),
Delete(),
GetMessages(),
SendMessage(),
RemoveMessages(),
PingPong()
],
2: [
Get(),
Save(),
Lock(),
GetMessages(),
SendMessage(),
RemoveMessages(),
PingPong()
]
}
MSG_TYPES = dict(
[(version, ([t.Request for t in processors] + [t.Response for t in processors] + [ExceptionResponse]))
for version, processors in MSG_PROCESSORS.iteritems()]
)
MSG_TYPES_LOOKUP = dict(
[(version, dict(zip(msg_types, range(len(msg_types)))))
for version, msg_types in MSG_TYPES.iteritems()]
)
MSG_TYPES_PROCESSOR_LOOKUP = dict(
[(version, dict([(p.Request, p) for p in processors] +
[(p.Response, p) for p in processors]))
for version, processors in MSG_PROCESSORS.iteritems()]
)
log.debug("MSG_TYPES: %r", MSG_TYPES)
log.debug("MSG_TYPES_LOOKUP: %r", MSG_TYPES_LOOKUP)
log.debug("MSG_TYPES_PROCESSOR_LOOKUP: %r", MSG_TYPES_PROCESSOR_LOOKUP)
VERSION_HEADER_FORMAT = '!H'
VERSION_HEADER_LENGTH = struct.calcsize(VERSION_HEADER_FORMAT)
# The first value must always be H and be the version
HEADER_FORMAT = {
# Version, Message type, Data length
2: '!BL',
# Version, Message type, Data length
3: '!BL'
}
HEADER_LENGTH = dict(
[(version, struct.calcsize(header_format))
for version, header_format in HEADER_FORMAT.iteritems()]
)
VERSION = sorted(HEADER_FORMAT.keys())[-1]
VERSIONS = HEADER_FORMAT.keys()
def get_processor_for_message(msg, version=VERSION):
return MSG_TYPES_PROCESSOR_LOOKUP[version][msg.__class__]
class UUSSProtocol(object):
def __init__(self, socket, config=None):
if isinstance(socket, lolsocket.LolSocket):
self.socket = socket
else:
self.socket = lolsocket.LolSocket(socket)
self.config = config or {}
self.fail_healthcheck = False
@staticmethod
def _parse_version_header(data):
(version,) = struct.unpack(VERSION_HEADER_FORMAT, data[:VERSION_HEADER_LENGTH])
log.debug("Received message version: %r", version)
if version not in VERSIONS:
raise UUSSProtocolException("Message version received is %r, we expected one of %r" % (version, VERSIONS))
remaining_data = data[VERSION_HEADER_LENGTH:]
return (version, remaining_data)
@staticmethod
def _parse_message_header(data, version):
header_length = HEADER_LENGTH[version]
(msg_type, msg_len) = struct.unpack(HEADER_FORMAT[version], data[:header_length])
log.debug("Received message header: %r, %r", msg_type, msg_len)
try:
msg_class = MSG_TYPES[version][msg_type]
except IndexError, e:
raise UUSSProtocolException("Invalid message type received: %r" % msg_type)
msg_data = data[header_length:]
if len(msg_data) != 0 and len(msg_data) != msg_len:
raise UUSSProtocolException("Length of data (%r) does not match the length set in the header (%r)" % (len(msg_data), msg_len))
return (msg_type, msg_len, msg_data)
@staticmethod
def _parse_message_body(msg_type, data, version):
#log.debug("data: %r", data)
msg = MSG_TYPES[version][msg_type]()
msg.ParseFromString(data)
if msg.__class__ is ExceptionResponse:
if 'ShardDown' in msg.message:
raise UUSSShardDownException("The shard for this userstate is down: %r\n%s" % (msg.message, msg.traceback))
else:
raise UUSSProtocolException("Exception received from UUSS server: %r\n%s" % (msg.message, msg.traceback))
return msg
@staticmethod
def _parse_message(data):
(version, remaining_data) = UUSSProtocol._parse_version_header(data)
(msg_type, msg_len, msg_data) = UUSSProtocol._parse_message_header(remaining_data, version)
return (version, UUSSProtocol._parse_message_body(msg_type, msg_data, version))
def _recv_version_header(self):
data = self.socket.recv_bytes(VERSION_HEADER_LENGTH)
return self._parse_version_header(data)[0]
def _recv_message_header(self, version):
data = self.socket.recv_bytes(HEADER_LENGTH[version])
return self._parse_message_header(data, version)[:-1]
def _recv_message_body(self, msg_type, msg_len):
# XXX(jpatrin): why does this not parse like the above 2?
return self.socket.recv_bytes(msg_len)
@staticmethod
def _encode_message(msg, version=VERSION):
data = msg.SerializeToString()
msg_type = MSG_TYPES_LOOKUP[version][msg.__class__]
header = struct.pack(VERSION_HEADER_FORMAT, version) + struct.pack(HEADER_FORMAT[version], msg_type, len(data))
return (header, data)
## public interface
def send_message(self, msg, version=VERSION):
self.socket.send_bytes(''.join(self._encode_message(msg, version)))
def recv_expected_message_class(self, expected_msg_class):
(version, msg) = self.recv_message()
if msg.__class__ is not expected_msg_class:
raise UUSSProtocolException("Message class %r expected, got %r instead: %r" % (expected_msg_class, msg.__class__, msg))
return (version, msg)
def recv_expected_message(self, expected_msg_class, expected_game, expected_user_id):
(version, msg) = self.recv_expected_message_class(expected_msg_class)
if msg.game != expected_game:
raise UUSSProtocolException("Game %r expected, got %r instead" % (expected_game, msg.game))
if msg.user_id != expected_user_id:
raise UUSSProtocolException("User ID %r expected, got %r instead" % (expected_user_id, msg.user_id))
return (version, msg)
def recv_message(self):
version = self._recv_version_header()
(msg_type, msg_len) = self._recv_message_header(version)
log.debug("msg_type: %r", msg_type)
log.debug("msg_len: %r", msg_len)
data = self._recv_message_body(msg_type, msg_len)
return (version, self._parse_message_body(msg_type, data, version))
|
brianr/uuss
|
proto.py
|
Python
|
mit
| 17,229
|
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
import profiles.urls
import accounts.urls
from . import views
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^users/', include(profiles.urls, namespace='profiles')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(accounts.urls, namespace='accounts')),
url(r'^post_url/$', views.HomePage.as_view(), name='post')
]
# User-uploaded files like profile pics need to be served in development
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Include django debug toolbar if DEBUG is on
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
Zedmor/powerball
|
src/powerball/urls.py
|
Python
|
mit
| 852
|
import graph
from depth_first_search import depth_first_search
from breadth_first_search import breadth_first_search
edges = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (2, 6),
(2, 7), (3, 8), (3, 9), (4, 10), (4, 11)]
G, _ = graph.create_graph(edges)
start_vertex = G.get_vertex(0)
breadth = breadth_first_search(G)
breadth(G, start_vertex)
depth = depth_first_search(G)
depth(G, start_vertex)
print('Undirected Case.')
print(edges)
print(' ')
print('==============================')
print('Breadth First traversal of G')
for edge in breadth.breadth_traversal:
print((edge.endPoints()[0].element(), edge.endPoints()[1].element()))
print('==============================')
print('Depth First traversal of G')
for edge in depth.depth_traversal:
print((edge.endPoints()[0].element(), edge.endPoints()[1].element()))
print(' ')
print('==============================')
print('==============================')
print(' ')
edges = [('a', 'b'), ('c', 'a'), ('c', 'b'),
('d', 'c'), ('d', 'e'), ('b', 'e')]
G, _ = graph.create_graph(edges, True)
start_vertex = G.get_vertex('a')
breadth = breadth_first_search(G)
breadth(G, start_vertex)
depth = depth_first_search(G)
depth(G, start_vertex)
print('Directed Case.')
print(edges)
print(' ')
print('==============================')
print('Breadth First traversal of G')
for edge in breadth.breadth_traversal:
print((edge.endPoints()[0].element(), edge.endPoints()[1].element()))
print('==============================')
print('Depth First traversal of G')
for edge in depth.depth_traversal:
print((edge.endPoints()[0].element(), edge.endPoints()[1].element()))
|
Sorrop/py-graph-algorithms
|
traversal_tests.py
|
Python
|
mit
| 1,800
|
import pdb
class TimingDiagram:
def print_diagram(self, xtsm_object):
pdb.set_trace()
seq = xtsm_object.XTSM.getActiveSequence()
cMap=seq.getOwnerXTSM().getDescendentsByType("ChannelMap")[0]
#channelHeir=cMap.createTimingGroupHeirarchy()
#channelRes=cMap.findTimingGroupResolutions()
#Parser out put node. Use TimingProffer
#Control arrays hold what is actually coming out.
seq.collectTimingProffers()
edge_timings = seq.TimingProffer.data['Edge']
class Edge:
def __init__(self, timing_group, channel_number, time, value, tag,
name, initial_value, holding_value):
self.timing_group = timing_group
self.channel_number = channel_number
self.time = time
self.value = value
self.tag = tag
self.max = 0
self.min = 0
self.name = name
self.holding_value = holding_value
self.initial_value = initial_value
def is_same(self,edge):
if ((self.timing_group == edge.timing_group) and
(self.channel_number == edge.channel_number) and
(self.time == edge.time) and
(self.value == edge.value) and
(self.tag == edge.tag)):
return True
else:
return False
edges = []
longest_name = 0
for edge in edge_timings:
for channel in cMap.Channel:
tgroup = int(channel.TimingGroup.PCDATA)
tgroupIndex = int(channel.TimingGroupIndex.PCDATA)
if tgroup == int(edge[0]) and tgroupIndex == int(edge[1]):
name = channel.ChannelName.PCDATA
init_val = ''
hold_val = ''
try:
init_val = channel.InitialValue.PCDATA
except AttributeError:
init_val = 'None '
try:
hold_val = channel.HoldingValue.PCDATA
except AttributeError:
hold_val = 'None '
if len(name) > longest_name:
longest_name = len(name)
edges.append(Edge(edge[0],edge[1],edge[2],edge[3],edge[4],
name, init_val,hold_val))
#pdb.set_trace()
unique_group_channels = []
for edge in edges:
is_found = False
for ugc in unique_group_channels:
if edge.is_same(ugc):
is_found = True
if not is_found:
unique_group_channels.append(edge)
from operator import itemgetter
edge_timings_by_group = sorted(edge_timings, key=itemgetter(2))
edge_timings_by_group_list = []
for edge in edge_timings_by_group:
edge_timings_by_group_list.append(edge.tolist())
#print edge_timings
for p in edge_timings_by_group_list: print p
unique_times = []
for edge in edges:
is_found = False
for t in unique_times:
if edge.time == t.time:
is_found = True
if not is_found:
unique_times.append(edge)
#pdb.set_trace()
for ugc in unique_group_channels:
s = ugc.name.rjust(longest_name)
current_edge = edges[0]
previous_edge = edges[0]
is_first = True
for t in unique_times:
is_found = False
for edge in edges:
if edge.timing_group == ugc.timing_group and edge.channel_number == ugc.channel_number and edge.time == t.time:
is_found = True
current_edge = edge
if is_first:
s = s + '|' + str('%7s' % str(current_edge.initial_value))
is_first = False
previous_edge.value = current_edge.initial_value
if previous_edge.value == 'None ':
previous_edge.value = 0
if is_found:
if current_edge.value > previous_edge.value:
s += '^' + str('%7s' % str(current_edge.value))
else:
s += 'v' + str('%7s' % str(current_edge.value))
previous_edge = current_edge
else:
s += '|' + '.'*7
s = s + '|' + str('%7s' % str(current_edge.holding_value))
print s
s = "Time (ms)".rjust(longest_name) + '|' + str('%7s' % str("Initial"))
for t in unique_times:
s += '|' + str('%7s' % str(t.time))
s = s + '|' + str('%7s' % str("Holding"))
print s
|
gemelkelabs/timing_system_software
|
server_py_files/utilities/timing_diagram.py
|
Python
|
mit
| 5,170
|
from rest_framework import status
from rest_framework.authtoken.models import Token
from django.utils.translation import ugettext_lazy as _
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAULTS
from drfpasswordless.utils import CallbackToken
User = get_user_model()
class AliasEmailVerificationTests(APITestCase):
def setUp(self):
api_settings.PASSWORDLESS_AUTH_TYPES = ['EMAIL']
api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS = 'noreply@example.com'
api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED = True
self.url = reverse('drfpasswordless:auth_email')
self.callback_url = reverse('drfpasswordless:auth_token')
self.verify_url = reverse('drfpasswordless:verify_email')
self.callback_verify = reverse('drfpasswordless:verify_token')
self.email_field_name = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME
self.email_verified_field_name = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME
def test_email_unverified_to_verified_and_back(self):
email = 'aaron@example.com'
email2 = 'aaron2@example.com'
data = {'email': email}
# create a new user
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user = User.objects.get(**{self.email_field_name: email})
self.assertNotEqual(user, None)
self.assertEqual(getattr(user, self.email_verified_field_name), False)
# Verify a token exists for the user, sign in and check verified again
callback = CallbackToken.objects.filter(user=user, type=CallbackToken.TOKEN_TYPE_AUTH, is_active=True).first()
callback_data = {'email': email, 'token': callback}
callback_response = self.client.post(self.callback_url, callback_data)
self.assertEqual(callback_response.status_code, status.HTTP_200_OK)
# Verify we got the token, then check and see that email_verified is now verified
token = callback_response.data['token']
self.assertEqual(token, Token.objects.get(user=user).key)
# Refresh and see that the endpoint is now verified as True
user.refresh_from_db()
self.assertEqual(getattr(user, self.email_verified_field_name), True)
# Change email, should result in flag changing to false
setattr(user, self.email_field_name, email2)
user.save()
user.refresh_from_db()
self.assertEqual(getattr(user, self.email_verified_field_name), False)
# Verify
self.client.force_authenticate(user)
verify_response = self.client.post(self.verify_url)
self.assertEqual(verify_response.status_code, status.HTTP_200_OK)
# Refresh User
user = User.objects.get(**{self.email_field_name: email2})
self.assertNotEqual(user, None)
self.assertNotEqual(getattr(user, self.email_field_name), None)
self.assertEqual(getattr(user, self.email_verified_field_name), False)
# Post callback token back.
verify_token = CallbackToken.objects.filter(user=user, type=CallbackToken.TOKEN_TYPE_VERIFY, is_active=True).first()
self.assertNotEqual(verify_token, None)
verify_callback_response = self.client.post(self.callback_verify, {'email': email2, 'token': verify_token.key})
self.assertEqual(verify_callback_response.status_code, status.HTTP_200_OK)
# Refresh User
user = User.objects.get(**{self.email_field_name: email2})
self.assertNotEqual(user, None)
self.assertNotEqual(getattr(user, self.email_field_name), None)
self.assertEqual(getattr(user, self.email_verified_field_name), True)
def tearDown(self):
api_settings.PASSWORDLESS_AUTH_TYPES = DEFAULTS['PASSWORDLESS_AUTH_TYPES']
api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS = DEFAULTS['PASSWORDLESS_EMAIL_NOREPLY_ADDRESS']
api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED = DEFAULTS['PASSWORDLESS_USER_MARK_MOBILE_VERIFIED']
class AliasMobileVerificationTests(APITestCase):
def setUp(self):
api_settings.PASSWORDLESS_TEST_SUPPRESSION = True
api_settings.PASSWORDLESS_AUTH_TYPES = ['MOBILE']
api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER = '+15550000000'
api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED = True
self.url = reverse('drfpasswordless:auth_mobile')
self.callback_url = reverse('drfpasswordless:auth_token')
self.verify_url = reverse('drfpasswordless:verify_mobile')
self.callback_verify = reverse('drfpasswordless:verify_token')
self.mobile_field_name = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME
self.mobile_verified_field_name = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME
def test_mobile_unverified_to_verified_and_back(self):
mobile = '+15551234567'
mobile2 = '+15557654321'
data = {'mobile': mobile}
# create a new user
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user = User.objects.get(**{self.mobile_field_name: mobile})
self.assertNotEqual(user, None)
self.assertEqual(getattr(user, self.mobile_verified_field_name), False)
# Verify a token exists for the user, sign in and check verified again
callback = CallbackToken.objects.filter(user=user, type=CallbackToken.TOKEN_TYPE_AUTH, is_active=True).first()
callback_data = {'mobile': mobile, 'token': callback}
callback_response = self.client.post(self.callback_url, callback_data)
self.assertEqual(callback_response.status_code, status.HTTP_200_OK)
# Verify we got the token, then check and see that email_verified is now verified
token = callback_response.data['token']
self.assertEqual(token, Token.objects.get(user=user).key)
# Refresh and see that the endpoint is now verified as True
user.refresh_from_db()
self.assertEqual(getattr(user, self.mobile_verified_field_name), True)
# Change mobile, should result in flag changing to false
setattr(user, self.mobile_field_name, '+15557654321')
user.save()
user.refresh_from_db()
self.assertEqual(getattr(user, self.mobile_verified_field_name), False)
# Verify
self.client.force_authenticate(user)
verify_response = self.client.post(self.verify_url)
self.assertEqual(verify_response.status_code, status.HTTP_200_OK)
# Refresh User
user = User.objects.get(**{self.mobile_field_name: mobile2})
self.assertNotEqual(user, None)
self.assertNotEqual(getattr(user, self.mobile_field_name), None)
self.assertEqual(getattr(user, self.mobile_verified_field_name), False)
# Post callback token back.
verify_token = CallbackToken.objects.filter(user=user, type=CallbackToken.TOKEN_TYPE_VERIFY, is_active=True).first()
self.assertNotEqual(verify_token, None)
verify_callback_response = self.client.post(self.callback_verify, {'mobile': mobile2, 'token': verify_token.key})
self.assertEqual(verify_callback_response.status_code, status.HTTP_200_OK)
# Refresh User
user = User.objects.get(**{self.mobile_field_name: mobile2})
self.assertNotEqual(user, None)
self.assertNotEqual(getattr(user, self.mobile_field_name), None)
self.assertEqual(getattr(user, self.mobile_verified_field_name), True)
def tearDown(self):
api_settings.PASSWORDLESS_TEST_SUPPRESSION = DEFAULTS['PASSWORDLESS_TEST_SUPPRESSION']
api_settings.PASSWORDLESS_AUTH_TYPES = DEFAULTS['PASSWORDLESS_AUTH_TYPES']
api_settings.PASSWORDLESS_MOBILE_NOREPLY_ADDRESS = DEFAULTS['PASSWORDLESS_MOBILE_NOREPLY_NUMBER']
api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED = DEFAULTS['PASSWORDLESS_USER_MARK_MOBILE_VERIFIED']
|
aaronn/django-rest-framework-passwordless
|
tests/test_verification.py
|
Python
|
mit
| 8,084
|
# -*- coding: utf-8 -*-
from __future__ import division
import matplotlib.pyplot as plt
import random
import numpy as np
class Player:
def __init__(self, state, q):
self.state = state
self.gain_matrix = np.array([[q, 0], [0, 1-q]])
def action_distribution(self, N, m, players):
adj_matrix = np.zeros((N, N)) #両隣と対戦する様にしました。
adj_matrix[N-1,0], adj_matrix[N-1,N-2] = 1, 1
for i in range(N-1):
adj_matrix[i, i-1], adj_matrix[i, i+1] = 1, 1
current_state = [player.state for player in players]
num_op_state_1 = np.dot(adj_matrix, current_state)
position = players.index(self)
act_dist = [(m-num_op_state_1[position])/m, num_op_state_1[position]/m]
return act_dist
def play(self):
act_dist = self.action_distribution(N, m, players)
payoff_vec = np.dot(self.gain_matrix, act_dist)
if payoff_vec[0] > payoff_vec[1]:
action = 0
elif payoff_vec[0] == payoff_vec[1]:
action = random.choice([0, 1])
else:
action = 1
return action
def update_player(self):
action = self.play()
self.state = action
def count_action(players):
actions = []
for player in players:
actions.append(player.state)
return actions.count(1)
num_0 = 15
num_1 = 1
N = num_0 + num_1
m = 2 #num_opponent
q = 1/3
T = 200
players = [Player(0, q) for i in range(num_0)]
players_1 = [Player(1, q) for i in range(num_1)]
for player_1 in players_1:
players.insert(random.randint(0, num_0), player_1)
transition = []
for t in range(T):
transition.append(count_action(players))
#print [player.action_distribution(N, m, players) for player in players]
i = random.randint(0, N-1)
players[i].update_player()
plt.plot(transition, label="action transition")
plt.legend()
plt.show()
|
TanaPanda/contagion
|
circle_network_0.py
|
Python
|
mit
| 2,084
|
#!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet encryption/locking
# Add python-bitcoinrpc to module search path:
from test_framework.authproxy import JSONRPCException
from test_framework.util import check_json_precision, initialize_chain, \
start_nodes, start_node, stop_nodes, wait_litecoinzds, litecoinzd_processes
import os
import sys
import shutil
import tempfile
import traceback
def check_array_result(object_array, to_match, expected):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
"""
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0:
raise AssertionError("No objects matched %s"%(str(to_match)))
def run_test(nodes, tmpdir):
# Encrypt wallet and wait to terminate
nodes[0].encryptwallet('test')
litecoinzd_processes[0].wait()
# Restart node 0
nodes[0] = start_node(0, tmpdir)
# Keep creating keys
addr = nodes[0].getnewaddress()
try:
addr = nodes[0].getnewaddress()
raise AssertionError('Keypool should be exhausted after one address')
except JSONRPCException,e:
assert(e.error['code']==-12)
# put three new keys in the keypool
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(3)
nodes[0].walletlock()
# drain the keys
addr = set()
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
# assert that four unique addresses were returned
assert(len(addr) == 4)
# the next one should fail
try:
addr = nodes[0].getrawchangeaddress()
raise AssertionError('Keypool should be exhausted after three addresses')
except JSONRPCException,e:
assert(e.error['code']==-12)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave litecoinzds and test.* datadir on exit or error")
parser.add_option("--srcdir", dest="srcdir", default="../../src",
help="Source directory containing litecoinzd/litecoinz-cli (default: %default%)")
parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
help="Root directory for datadirs")
(options, args) = parser.parse_args()
os.environ['PATH'] = options.srcdir+":"+os.environ['PATH']
check_json_precision()
success = False
nodes = []
try:
print("Initializing test directory "+options.tmpdir)
if not os.path.isdir(options.tmpdir):
os.makedirs(options.tmpdir)
initialize_chain(options.tmpdir)
nodes = start_nodes(1, options.tmpdir, extra_args=[['-experimentalfeatures', '-developerencryptwallet']])
run_test(nodes, options.tmpdir)
success = True
except AssertionError as e:
print("Assertion failed: "+e.message)
except JSONRPCException as e:
print("JSONRPC error: "+e.error['message'])
traceback.print_tb(sys.exc_info()[2])
except Exception as e:
print("Unexpected exception caught during testing: "+str(sys.exc_info()[0]))
traceback.print_tb(sys.exc_info()[2])
if not options.nocleanup:
print("Cleaning up")
stop_nodes(nodes)
wait_litecoinzds()
shutil.rmtree(options.tmpdir)
if success:
print("Tests successful")
sys.exit(0)
else:
print("Failed")
sys.exit(1)
# refill keypool with three new addresses
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(3)
nodes[0].walletlock()
# drain them by mining
nodes[0].generate(1)
nodes[0].generate(1)
nodes[0].generate(1)
nodes[0].generate(1)
try:
nodes[0].generate(1)
raise AssertionError('Keypool should be exhausted after three addresses')
except JSONRPCException,e:
assert(e.error['code']==-12)
if __name__ == '__main__':
main()
|
litecoinz-project/litecoinz
|
qa/rpc-tests/keypool.py
|
Python
|
mit
| 4,852
|
import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = random.Random(42)
rand_int = lambda: rand.randint(4, 10)
colors.append(('one random color', rand_color.generate()))
i = rand_int()
colors.append((
"%d random colors" % i,
rand_color.generate(count=i)
))
# test all hues
for hue in hues:
i = rand_int()
colors.append((
"%d random colors with %s hue" % (i, hue),
rand_color.generate(hue=hue, count=i)
))
# test all luminosities
for luminosity in luminosities:
i = rand_int()
colors.append((
"%d random colors with %s luminosity" % (i, luminosity),
rand_color.generate(luminosity=luminosity, count=i)
))
# test random combinations
for _ in range(50):
i = rand_int()
hue = random.choice(hues)
luminosity = random.choice(luminosities)
format_ = random.choice(formats)
colors.append((
"%d random colors with %s hue, %s luminosity, and %s format"
% (i, hue, luminosity, format_),
rand_color.generate(hue=hue, luminosity=luminosity,
format_=format_, count=i)
))
color_rows = colors_to_rows(colors)
html = generate_html(color_rows)
with open('randomcolors.html', 'w') as f:
f.write(html)
def colors_to_rows(colors):
s = ""
for color_name, colors in colors:
s += "<tr>"
s += "<td>%s</td>" % (color_name)
s += "<td>"
for color in colors:
s += "<div class='color' style='background-color:%s'></div>" % color
s += "</td>"
s += "</tr>"
return s
def generate_html(table_rows):
return """
<!DOCTYPE html>
<html lang="en">
<head>
<title>randomcolor test</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style>
.color {
height: 30px;
width: 30px;
border-radius: 30px;
display: inline-block;
}
</style>
</head>
<body>
<div class="container">
<div class="row col-md-10 col-md-offset-1">
<h1>Random Color Test</h1>
<table class="table">
%s
</table>
</div>
</body>
</html>
""" % table_rows
if __name__ == "__main__":
main()
|
kevinwuhoo/randomcolor-py
|
tests/test_randomcolor_visual.py
|
Python
|
mit
| 2,617
|
from utils import instrument
from azove.utils import recursive_int_to_big_endian
import mock
@given(u'a packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_packet('this is a test packet')
@when(u'peer.send_packet is called') # noqa
def step_impl(context):
context.peer.send_packet(context.packet)
@when(u'all data with the peer is processed') # noqa
def step_impl(context):
context.peer.run()
@then(u'the packet sent through connection should be the given packet') # noqa
def step_impl(context):
assert context.sent_packets == [context.packet]
@when(u'peer.send_Hello is called') # noqa
def step_impl(context):
context.peer.send_Hello()
@then(u'the packet sent through connection should be a Hello packet') # noqa
def step_impl(context):
packet = context.packeter.dump_Hello()
assert context.sent_packets == [packet]
@given(u'a valid Hello packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Hello()
@given(u'a Hello packet with protocol version incompatible') # noqa
def step_impl(context):
packeter = context.packeter
data = [packeter.cmd_map_by_name['Hello'],
'incompatible_protocal_version',
packeter.NETWORK_ID,
packeter.CLIENT_ID,
packeter.config.getint('network', 'listen_port'),
packeter.CAPABILITIES,
packeter.config.get('wallet', 'coinbase')
]
context.packet = packeter.dump_packet(data)
@given(u'a Hello packet with network id incompatible') # noqa
def step_impl(context):
packeter = context.packeter
data = [packeter.cmd_map_by_name['Hello'],
packeter.PROTOCOL_VERSION,
'incompatible_network_id',
packeter.CLIENT_ID,
packeter.config.getint('network', 'listen_port'),
packeter.CAPABILITIES,
packeter.config.get('wallet', 'coinbase')
]
context.packet = packeter.dump_packet(data)
@when(u'peer.send_Hello is instrumented') # noqa
def step_impl(context):
context.peer.send_Hello = instrument(context.peer.send_Hello)
@then(u'peer.send_Hello should be called once') # noqa
def step_impl(context):
func = context.peer.send_Hello
assert func.call_count == 1
@when(u'peer.send_Disconnect is instrumented') # noqa
def step_impl(context):
context.peer.send_Disconnect = instrument(context.peer.send_Disconnect)
@when(u'the packet is received from peer') # noqa
def step_impl(context):
context.add_recv_packet(context.packet)
@then(u'peer.send_Disconnect should be called once with args: reason') # noqa
def step_impl(context):
func = context.peer.send_Disconnect
assert func.call_count == 1
assert len(func.call_args[0]) == 1 or 'reason' in func.call_args[1]
@when(u'peer.send_Ping is called') # noqa
def step_impl(context):
context.peer.send_Ping()
@then(u'the packet sent through connection should be a Ping packet') # noqa
def step_impl(context):
packet = context.packeter.dump_Ping()
assert context.sent_packets == [packet]
@given(u'a Ping packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Ping()
@when(u'peer.send_Pong is instrumented') # noqa
def step_impl(context):
context.peer.send_Pong = instrument(context.peer.send_Pong)
@then(u'peer.send_Pong should be called once') # noqa
def step_impl(context):
func = context.peer.send_Pong
assert func.call_count == 1
@when(u'peer.send_Pong is called') # noqa
def step_impl(context):
context.peer.send_Pong()
@then(u'the packet sent through connection should be a Pong packet') # noqa
def step_impl(context):
packet = context.packeter.dump_Pong()
assert context.sent_packets == [packet]
@given(u'a Pong packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Pong()
@when(u'handler for a disconnect_requested signal is registered') # noqa
def step_impl(context):
from pyethereum.signals import peer_disconnect_requested
context.disconnect_requested_handler = mock.MagicMock()
peer_disconnect_requested.connect(context.disconnect_requested_handler)
@when(u'peer.send_Disconnect is called') # noqa
def step_impl(context):
context.peer.send_Disconnect()
@then(u'the packet sent through connection should be' # noqa
' a Disconnect packet')
def step_impl(context):
packet = context.packeter.dump_Disconnect()
assert context.sent_packets == [packet]
@then(u'the disconnect_requested handler should be called once' # noqa
' after sleeping for at least 2 seconds')
def step_impl(context):
import time # time is already pathced for mocks
assert context.disconnect_requested_handler.call_count == 1
sleeping = sum(x[0][0] for x in time.sleep.call_args_list)
assert sleeping >= 2
@given(u'a Disconnect packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Disconnect()
@then(u'the disconnect_requested handler should be called once') # noqa
def step_impl(context):
assert context.disconnect_requested_handler.call_count == 1
@when(u'peer.send_GetPeers is called') # noqa
def step_impl(context):
context.peer.send_GetPeers()
@then(u'the packet sent through connection should be' # noqa
' a GetPeers packet')
def step_impl(context):
packet = context.packeter.dump_GetPeers()
assert context.sent_packets == [packet]
@given(u'a GetPeers packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_GetPeers()
@given(u'peers data') # noqa
def step_impl(context):
context.peers_data = [
['127.0.0.1', 1234, 'local'],
['1.0.0.1', 1234, 'remote'],
]
@when(u'getpeers_received signal handler is connected') # noqa
def step_impl(context):
from pyethereum.signals import getpeers_received
handler = mock.MagicMock()
context.getpeers_received_handler = handler
getpeers_received.connect(handler)
@then(u'the getpeers_received signal handler should be called once') # noqa
def step_impl(context):
assert context.getpeers_received_handler.call_count == 1
@when(u'peer.send_Peers is called') # noqa
def step_impl(context):
context.peer.send_Peers(context.peers_data)
@then(u'the packet sent through connection should be a Peers packet' # noqa
' with the peers data')
def step_impl(context):
assert context.sent_packets == [
context.packeter.dump_Peers(context.peers_data)]
@given(u'a Peers packet with the peers data') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Peers(context.peers_data)
@when(u'handler for new_peers_received signal is registered') # noqa
def step_impl(context):
context.new_peer_received_handler = mock.MagicMock()
from pyethereum.signals import peer_addresses_received
peer_addresses_received.connect(context.new_peer_received_handler)
@then(u'the new_peers_received handler should be called once' # noqa
' with all peers')
def step_impl(context):
call_args = context.new_peer_received_handler.call_args_list[0]
call_peers = call_args[1]['addresses']
assert len(call_peers) == len(context.peers_data)
pairs = zip(call_peers, context.peers_data)
for call, peer in pairs:
assert call == peer
#assert call[1]['address'] == peer
@when(u'peer.send_GetTransactions is called') # noqa
def step_impl(context):
context.peer.send_GetTransactions()
@then(u'the packet sent through connection should be' # noqa
' a GetTransactions packet')
def step_impl(context):
packet = context.packeter.dump_GetTransactions()
assert context.sent_packets == [packet]
@given(u'a GetTransactions packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_GetTransactions()
@given(u'transactions data') # noqa
def step_impl(context):
context.transactions_data = [
['nonce-1', 'receiving_address-1', 1],
['nonce-2', 'receiving_address-2', 2],
['nonce-3', 'receiving_address-3', 3],
]
@when(u'gettransactions_received signal handler is connected') # noqa
def step_impl(context):
from pyethereum.signals import gettransactions_received
handler = mock.MagicMock()
context.gettransactions_received_handler = handler
gettransactions_received.connect(handler)
@then(u'the gettransactions_received signal handler' # noqa
' should be called once')
def step_impl(context):
assert context.gettransactions_received_handler.call_count == 1
@when(u'peer.send_Transactions is called') # noqa
def step_impl(context):
context.peer.send_Transactions(context.transactions_data)
@then(u'the packet sent through connection should be' # noqa
' a Transactions packet with the transactions data')
def step_impl(context):
packet = context.packeter.dump_Transactions(context.transactions_data)
assert context.sent_packets == [packet]
@given(u'a Transactions packet with the transactions data') # noqa
def step_impl(context):
packet = context.packeter.dump_Transactions(context.transactions_data)
context.packet = packet
@when(u'handler for a new_transactions_received signal is registered') # noqa
def step_impl(context):
context.new_transactions_received_handler = mock.MagicMock()
from pyethereum.signals import remote_transactions_received
remote_transactions_received.connect(
context.new_transactions_received_handler)
@then(u'the new_transactions_received handler' # noqa
' should be called once with the transactions data')
def step_impl(context):
mock = context.new_transactions_received_handler
assert mock.call_count == 1
assert mock.call_args[1]['transactions'] == recursive_int_to_big_endian(
context.transactions_data)
@given(u'blocks data') # noqa
def step_impl(context):
# FIXME here we need real blocks.Block objects
context.blocks_data = [
['block_headerA', ['txA1', 'txA2'], ['uncleA1', 'uncleA2']],
['block_headerB', ['txB', 'txB'], ['uncleB', 'uncleB2']],
]
@when(u'peer.send_Blocks is called') # noqa
def step_impl(context):
context.peer.send_Blocks(context.blocks_data)
@then(u'the packet sent through connection should be' # noqa
' a Blocks packet with the blocks data')
def step_impl(context):
packet = context.packeter.dump_Blocks(context.blocks_data)
assert context.sent_packets == [packet]
@given(u'a Blocks packet with the blocks data') # noqa
def step_impl(context):
context.packet = context.packeter.dump_Blocks(context.blocks_data)
@when(u'handler for a new_blocks_received signal is registered') # noqa
def step_impl(context):
context.new_blocks_received_handler = mock.MagicMock()
from pyethereum.signals import remote_blocks_received
remote_blocks_received.connect(context.new_blocks_received_handler)
@then(u'the new_blocks_received handler should be' # noqa
' called once with the blocks data')
def step_impl(context):
context.new_blocks_received_handler = mock.MagicMock()
from pyethereum.signals import remote_blocks_received
remote_blocks_received.connect(
context.new_blocks_received_handler)
@given(u'a GetChain request data') # noqa
def step_impl(context):
context.request_data = ['Parent1', 'Parent2', 3]
@when(u'peer.send_GetChain is called withe the request data') # noqa
def step_impl(context):
context.peer.send_GetChain(context.request_data)
@then(u'the packet sent through connection' # noqa
' should be a GetChain packet')
def step_impl(context):
packet = context.packeter.dump_GetChain(context.request_data)
assert context.sent_packets == [packet]
@given(u'a GetChain packet with the request data') # noqa
def step_impl(context):
context.packet = context.packeter.dump_GetChain(context.request_data)
@given(u'a chain data provider') # noqa
def step_impl(context):
from pyethereum.signals import (local_chain_requested)
def handler(sender, **kwargs):
pass
context.blocks_requested_handler = handler
local_chain_requested.connect(handler)
@when(u'peer.send_Blocks is instrumented') # noqa
def step_impl(context):
context.peer.send_Blocks = instrument(context.peer.send_Blocks)
@when(u'peer.send_NotInChain is called') # noqa
def step_impl(context):
context.peer.send_NotInChain('some hash')
@then(u'the packet sent through connection should' # noqa
' be a NotInChain packet')
def step_impl(context):
packet = context.packeter.dump_NotInChain('some hash')
assert context.sent_packets == [packet]
@given(u'a NotInChain packet') # noqa
def step_impl(context):
context.packet = context.packeter.dump_NotInChain('some hash')
|
elkingtowa/azove
|
features/steps/peer.py
|
Python
|
mit
| 12,702
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smarturl.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
ioiogoo/SmartUrl
|
manage.py
|
Python
|
mit
| 806
|
'''
Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import pandas as pd
import pylab as plt
import matplotlib as mpl
from matplotlib.cm import *
import os,sys;home=os.path.expanduser('~') +'/'
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size':20}) ;
mpl.rc('text', usetex=True)
x=np.arange(0,1,1e-5)[1:-1]
s=0.01
def sig(z): return 1./(1+np.exp(-z))
fig=plt.figure(figsize=(30,10), dpi=100)
fig.hold(True)
y_appr=np.log(x)- np.log(1-x)
y=np.log(x)- (1+s)*np.log(1-x)
x.shape
df=pd.DataFrame([x,y,y_appr],index=['x','y','z']).T
plt.subplot(1,2,1)
plt.plot(y_appr,x, color='red',linewidth=2, label='$\sigma(st/2-c)$')
plt.plot(y,x, color='blue',linewidth=2,label='$x_t$')
plt.xlim([-5,5]);plt.legend(loc='upper left')
plt.ylabel('$x_t$')
plt.xlabel('$st/2-c$')
plt.grid()
plt.subplot(1,2,2)
print (y_appr-y)
plt.plot(y,sig(y)-x, linewidth=2,label='Error');plt.legend(loc='upper left')
plt.ylabel('$|x_t-\sigma(st/2-c)|$')
plt.xlabel('$st/2-c$')
plt.xlim([-5,10])
plt.grid()
plt.suptitle('Approximation vs Exact Value of $x_t$ for $s=${}'.format(s))
# plt.savefig(home+'out/vineet/plots/apprx.png')
plt.show()
|
airanmehr/bio
|
Scripts/TimeSeriesPaper/Plot/DirectvsRNN.py
|
Python
|
mit
| 1,198
|
"""
The MIT License (MIT)
Copyright (c)2013 Rich Friedel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
'''
Attendance -
0 pts per class missed up to 3 classes missed
2 pts per class missed after 3 classes missed
7 missed classes results in automatic failure
'''
# TODO Create function to handle missed classes
def avg_exam_grade(lec_exams):
#TODO Finish writing documentation for this function
""" (list) -> float
Returns the average of all exam grades passed as lec_exams
If the second exam grade is higher than that first exam grade
take the difference of the two grades, divide that by two and
add the total to the first exam grade
"""
# Create a temp list
temp_list = []
# Load the temp list with the lec_exams values
for item in lec_exams:
temp_list.append(item)
# If the second grade is higher than the first grade
if temp_list[1] > temp_list[0]:
dif = temp_list[1] - temp_list[0]
temp_list[0] += dif / 2
return sum(temp_list) / len(temp_list)
def avg_quiz_grade(lec_quizzes):
#TODO Finish writing documentation for this function
"""
Returns the average of lec_quizzes after removing the lowest
grade in the list
@param lec_quizzes:
@return:
"""
# Create a temp list because I don't want to alter the original list
temp_list = []
for item in lec_quizzes:
temp_list.append(item)
# Find the index that the low value occurs
index_of_low_val = temp_list.index(min(temp_list))
# Remove the value
del temp_list[index_of_low_val]
return (sum(temp_list) / (len(temp_list) * 100)) * 100
def weighted_exam_grade(lec_exams: list) -> float:
#TODO Finish writing documentation for this function
"""
The formula => (sum(lec_exams) / 4) * 0.7
"""
return avg_exam_grade(lec_exams) * 0.7
def weighted_final_exam_grade(final_exam: float) -> float:
#TODO Finish writing documentation for this function
return final_exam * 0.2
def weighted_quiz_grade(lec_quizzes: list) -> float:
#TODO Finish writing documentation for this function
"""
Returns the weighted result of lec_quizzes after removing
the lowest grade in the list
@param lec_quizzes: List of quizzes
@return: float
"""
return (avg_quiz_grade(lec_quizzes)) * 0.1
def raw_grade(lec_exams: list, final_exam: float, lec_quizzes: list) -> float:
#TODO Finish writing documentation for this function
"""
@todo Write documentation for this function
@param lec_exams:
@param final_exam:
@param lec_quizzes:
@return:
"""
return (sum(lec_exams) + sum(lec_quizzes) + final_exam) / (1 + len(lec_exams) + len(lec_quizzes))
def weighted_grade(lec_exams, final_exam, lec_quizzes):
#TODO Finish writing documentation for this function
"""
@todo Write documentation for this function
@param lec_exams: List of the exam grades
@param final_exam: The final exam score
@param lec_quizzes: List of quiz grades
@return: A float of the processed values
"""
return (weighted_exam_grade(lec_exams) + weighted_quiz_grade(lec_quizzes) + weighted_final_exam_grade(
final_exam)) * 0.75
|
rf3Studios/anatomy_calc_python
|
anatomy_calc/lec_func.py
|
Python
|
mit
| 4,209
|
# Copyright 2015 David Wang. All rights reserved.
# Use of this source code is governed by MIT license.
# Please see LICENSE file
# WebSpark
# Spark web service demo
# version 0.2
# use REPL or define sc SparkContext
import urllib2, urllib
import math
import time
import traceback
# Spark Web Application demo with parallel processing
# see demoservice function
ServerAddr="http://<enter WebSpark IP address here>:8001"
RegisterURL=ServerAddr + "/addapi?"
RespondURL=ServerAddr + "/respond?"
errwaitseconds = 3
element = '<li class="list-group-item">first prime above %d is %d</li>'
with open('template.html') as f:
template = f.read()
def slow_isprime(num):
if num<2:
return False
for i in range(2, int(math.sqrt(num))+1):
if num%i==0:
return False
return True
def firstprimeabove(num):
i=num+1
while True:
if slow_isprime(i):
return i
i+=1
servicename = 'demo'
# Spark Web Application demo
def demo(url):
rawdata = range(1000, 20000, 1100)
data = sc.parallelize(rawdata)
above=data.map(lambda x: (x, firstprimeabove(x))).collect()
primelist=[element%x for x in above]
response = template % ' '.join(primelist)
return response
def parserequest(rawrequest):
lines = rawrequest.split('\n')
if len(lines)<4:
print 'incorrect WebSpark request'
else:
name = lines[0]
url = lines[1]
remoteaddr = lines[2]
header = lines[3:]
return name, url, remoteaddr, header
st =''
# publish web service with WebSpark
while True:
try:
url = RegisterURL + urllib.urlencode({'name': servicename})
conn = urllib2.urlopen(url)
data = conn.read()
conn.close()
name, clienturl, remoteaddr, header = parserequest(data)
print name, clienturl, remoteaddr, header
response = demo(clienturl)
url = RespondURL + urllib.urlencode({'name': name})
conn = urllib2.urlopen(url, response)
conn.close()
except Exception as ex:
print 'error connecting to WebSpark at', ServerAddr
traceback.print_exc()
time.sleep(errwaitseconds)
continue
|
mdavid8/WebSpark
|
spark_webservice_demo.py
|
Python
|
mit
| 1,997
|
import types
from sikwidgets.region_group import RegionGroup
from sikwidgets.util import to_snakecase
from sikwidgets.widgets import *
def gen_widget_method(widget_class):
def widget(self, *args, **kwargs):
return self.create_widget(widget_class, *args, **kwargs)
return widget
class Window(RegionGroup):
def __init__(self, region, parent=None):
# FIXME: this is hacky
RegionGroup.__init__(self, parent)
# manually set the region to the given one rather
# than the region from the parent
self.search_region = region
self.region = region
self.widgets = []
self.windows = []
self.add_widget_methods()
self.contains()
# FIXME: str() shouldn't return a URI.. use image_folder() method for this
def __str__(self):
uri = to_snakecase(self.__class__.__name__)
if self.parent:
uri = os.path.join(str(self.parent), uri)
return uri
def create_image_folders(self):
for widget in self.widgets:
widget.create_image_folder()
for window in self.windows:
window.create_image_folders()
def capture_screenshots(self):
for widget in self.widgets:
widget.capture_screenshots()
for window in self.windows:
window.capture_screenshots()
def contains(self):
pass
# TODO: use some basic statistics to decide
# if we see the window or not
def exists(self):
#pop_size = len(self.widgets)
#n = sample_size(pop_size)
#random.sample(self.widgets, n)
seen_widgets = 0
unseen_widgets = 0
for widget in self.widgets:
if seen_widgets >= 10:
# we're confident enough it exists
return True
if widget.exists():
seen_widgets += 1
else:
unseen_widgets += 1
if seen_widgets > 2 * unseen_widgets + 1:
return True
if seen_widgets >= unseen_widgets:
return True
return False
def create_widget(self, widget_class, *args, **kwargs):
widget = widget_class(self, *args, **kwargs)
self.widgets.append(widget)
return widget
def add_widget_methods(self):
for class_name in instantiable_widget_class_names:
widget_class = eval(class_name)
method = types.MethodType(gen_widget_method(widget_class), self, self.__class__)
# take the class, get its name in string form, and convert to snake case
method_name = to_snakecase(widget_class.__name__)
setattr(self, method_name, method)
def menu(self, menu_class, *args, **kwargs):
return self.create_widget(menu_class, *args, **kwargs)
def page(self, page_class, *args, **kwargs):
return self.create_widget(page_class, *args, **kwargs)
def window(self, window_class):
# since the region for a child window may actually be larger than
# the region for this window, we should default to passing the
# entire screen
window = window_class(self.region.getScreen(), self)
self.windows.append(window)
return window
|
griffy/sikwidgets
|
sikwidgets/window.py
|
Python
|
mit
| 3,281
|
def b():
print("hooora!")
dic1 = {1: 2, 1: 4}
for i in dic1.items():
if 'a' == i:
b()
else:
break
print ":("
|
amiraliakbari/sharif-mabani-python
|
by-session/ta-922/j6/a1.py
|
Python
|
mit
| 136
|
#!/usr/bin/env python
# pylint: disable=invalid-name
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import sys
from problembaseclass import ProblemBaseClass
class Problem5(ProblemBaseClass):
"""
@class Solution for Problem 5
@brief
"""
def __init__(self, range):
self.result = None
self.range = range
def compute(self):
notfound=True
val=0
while(notfound):
notfound = False
val = val + 1
for n in range(1, self.range):
if (val % n):
notfound = True
self.result = val
if __name__ == '__main__':
problem = Problem5(10)
problem.compute()
print problem.result
del problem
problem = Problem5(20)
problem.compute()
print problem.result #232792560
del problem
|
jakubczaplicki/projecteuler
|
problem005.py
|
Python
|
mit
| 1,000
|
import quickfix
import copy
import uuid
import random
import datetime
import yaml
from twisted.internet import task
from sim import (FixSimError, FixSimApplication, create_fix_version,
instance_safe_call, create_logger, IncrementID, load_yaml)
class Subscription(object):
def __init__(self, symbol):
super(Subscription, self).__init__()
self.symbol = symbol
self.currency = self.symbol.split("/")[0]
def __repr__(self):
return "<Subscription %s>" % self.symbol
class Subscriptions(object):
def __init__(self):
self.subscriptions = {}
def add(self, subscription):
if subscription.symbol in self.subscriptions:
raise KeyError("Subscription for symbol has already exist")
self.subscriptions[subscription.symbol] = subscription
def get(self, symbol):
subscription = self.subscriptions.get(symbol, None)
return subscription
def __iter__(self):
return self.subscriptions.values().__iter__()
class OrderBook(object):
def __init__(self):
self.quotes = []
def setSnapshot(self, snaphot):
raise NotImplementedError()
def __iter__(self):
return self.quotes.__iter__()
def get(self, quoteID):
for quote in self.quotes:
if quote.id == quoteID:
return quote
return None
class IDGenerator(object):
def __init__(self):
self._orderID = IncrementID()
self._reqID = IncrementID()
def orderID(self):
return self._orderID.generate()
def reqID(self):
return self._reqID.generate()
def create_initiator(initiator_config, simulation_config):
def create_subscriptions(instruments):
result = Subscriptions()
for instrument in instruments:
subscription = Subscription(instrument['symbol'])
result.add(subscription)
return result
settings = quickfix.SessionSettings(initiator_config)
config = load_yaml(simulation_config)
fix_version = create_fix_version(config)
subscriptions = create_subscriptions(config['instruments'])
logger = create_logger(config)
subscribe_interval = config.get('subscribe_interval', 1)
skip_snapshot_chance = config.get('skip_snapshot_chance', 0)
application = Client(fix_version, logger, skip_snapshot_chance, subscribe_interval, subscriptions)
storeFactory = quickfix.FileStoreFactory(settings)
logFactory = quickfix.ScreenLogFactory(settings)
initiator = quickfix.SocketInitiator(application, storeFactory, settings, logFactory)
return initiator
class Snapshot(object):
def __init__(self, symbol):
self.symbol = symbol
self.bid = []
self.ask = []
def getRandomQuote(self):
is_bid = random.randrange(0, 2)
if is_bid:
quotes = self.bid
else:
quotes = self.ask
quote = random.choice(quotes)
return quote
def addBid(self, quote):
quote.side = Quote.SELL
self.bid.append(quote)
def addAsk(self, quote):
quote.side = quote.BUY
self.ask.append(quote)
def __repr__(self):
return "Snapshot %s\n BID: %s\n ASK: %s" % (self.symbol, self.bid, self.ask)
class Quote(object):
SELL = '2'
BUY = '1'
def __init__(self):
super(Quote, self).__init__()
self.side = None
self.symbol = None
self.currency = None
self.price = None
self.size = None
self.id = None
def __repr__(self):
return "(%s %s %s, %s)" % (str(self.id), self.side, str(self.price), str(self.size))
class Client(FixSimApplication):
MKD_TOKEN = "MKD"
def __init__(self, fixVersion, logger, skipSnapshotChance, subscribeInterval, subscriptions):
super(Client, self).__init__(fixVersion, logger)
self.skipSnapshotChance = skipSnapshotChance
self.subscribeInterval = subscribeInterval
self.subscriptions = subscriptions
self.orderSession = None
self.marketSession = None
self.idGen = IDGenerator()
self.loop = task.LoopingCall(self.subscribe)
self.loop.start(self.subscribeInterval, True)
def onCreate(self, sessionID):
pass
def onLogon(self, sessionID):
sid = str(sessionID)
# print "ON LOGON sid", sid
if sid.find(self.MKD_TOKEN) != -1:
self.marketSession = sessionID
self.logger.info("FIXSIM-CLIENT MARKET SESSION %s", self.marketSession)
else:
self.orderSession = sessionID
self.logger.info("FIXSIM-CLIENT ORDER SESSION %s", self.orderSession)
def onLogout(self, sessionID):
# print "ON LOGOUT"
return
def toAdmin(self, sessionID, message):
# print "TO ADMIN", message
return
def fromAdmin(self, sessionID, message):
# print "FROM ADMIN"
return
def toApp(self, sessionID, message):
# print "TO APP"
return
def subscribe(self):
if self.marketSession is None:
self.logger.info("FIXSIM-CLIENT Market session is none, skip subscribing")
return
for subscription in self.subscriptions:
message = self.fixVersion.MarketDataRequest()
message.setField(quickfix.MDReqID(self.idGen.reqID()))
message.setField(quickfix.SubscriptionRequestType(quickfix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES))
message.setField(quickfix.MDUpdateType(quickfix.MDUpdateType_FULL_REFRESH))
message.setField(quickfix.MarketDepth(0))
message.setField(quickfix.MDReqID(self.idGen.reqID()))
relatedSym = self.fixVersion.MarketDataRequest.NoRelatedSym()
relatedSym.setField(quickfix.Product(quickfix.Product_CURRENCY))
relatedSym.setField(quickfix.SecurityType(quickfix.SecurityType_FOREIGN_EXCHANGE_CONTRACT))
relatedSym.setField(quickfix.Symbol(subscription.symbol))
message.addGroup(relatedSym)
group = self.fixVersion.MarketDataRequest.NoMDEntryTypes()
group.setField(quickfix.MDEntryType(quickfix.MDEntryType_BID))
message.addGroup(group)
group.setField(quickfix.MDEntryType(quickfix.MDEntryType_BID))
message.addGroup(group)
self.sendToTarget(message, self.marketSession)
def onMarketDataSnapshotFullRefresh(self, message, sessionID):
skip_chance = random.choice(range(1, 101))
if self.skipSnapshotChance > skip_chance:
self.logger.info("FIXSIM-CLIENT onMarketDataSnapshotFullRefresh skip making trade with random choice %d", skip_chance)
return
fix_symbol = quickfix.Symbol()
message.getField(fix_symbol)
symbol = fix_symbol.getValue()
snapshot = Snapshot(symbol)
group = self.fixVersion.MarketDataSnapshotFullRefresh.NoMDEntries()
fix_no_entries = quickfix.NoMDEntries()
message.getField(fix_no_entries)
no_entries = fix_no_entries.getValue()
for i in range(1, no_entries + 1):
message.getGroup(i, group)
price = quickfix.MDEntryPx()
size = quickfix.MDEntrySize()
currency = quickfix.Currency()
quote_id = quickfix.QuoteEntryID()
group.getField(quote_id)
group.getField(currency)
group.getField(price)
group.getField(size)
quote = Quote()
quote.price = price.getValue()
quote.size = size.getValue()
quote.currency = currency.getValue()
quote.id = quote_id.getValue()
fix_entry_type = quickfix.MDEntryType()
group.getField(fix_entry_type)
entry_type = fix_entry_type.getValue()
if entry_type == quickfix.MDEntryType_BID:
snapshot.addBid(quote)
elif entry_type == quickfix.MDEntryType_OFFER:
snapshot.addAsk(quote)
else:
raise RuntimeError("Unknown entry type %s" % str(entry_type))
self.makeOrder(snapshot)
def makeOrder(self, snapshot):
self.logger.info("FIXSIM-CLIENT Snapshot received %s", str(snapshot))
quote = snapshot.getRandomQuote()
self.logger.info("FIXSIM-CLIENT make order for quote %s", str(quote))
order = self.fixVersion.NewOrderSingle()
order.setField(quickfix.HandlInst(quickfix.HandlInst_AUTOMATED_EXECUTION_ORDER_PUBLIC_BROKER_INTERVENTION_OK))
order.setField(quickfix.SecurityType(quickfix.SecurityType_FOREIGN_EXCHANGE_CONTRACT))
order.setField(quickfix.OrdType(quickfix.OrdType_PREVIOUSLY_QUOTED))
order.setField(quickfix.ClOrdID(self.idGen.orderID()))
order.setField(quickfix.QuoteID(quote.id))
order.setField(quickfix.SecurityDesc("SPOT"))
order.setField(quickfix.Symbol(snapshot.symbol))
order.setField(quickfix.Currency(quote.currency))
order.setField(quickfix.Side(quote.side))
order.setField(quickfix.OrderQty(quote.size))
order.setField(quickfix.FutSettDate("SP"))
order.setField(quickfix.Price(quote.price))
order.setField(quickfix.TransactTime())
order.setField(quickfix.TimeInForce(quickfix.TimeInForce_IMMEDIATE_OR_CANCEL))
self.sendToTarget(order, self.orderSession)
def onExecutionReport(self, message, sessionID):
self.logger.info("FIXSIM-CLIENT EXECUTION REPORT %s", str(message))
def dispatchFromApp(self, msgType, message, beginString, sessionID):
if msgType == '8':
self.onExecutionReport(message, sessionID)
elif msgType == 'W':
self.onMarketDataSnapshotFullRefresh(message, sessionID)
|
gloryofrobots/fixsim
|
fixsim/client.py
|
Python
|
mit
| 9,845
|
#-*- coding: utf-8 -*-
#既存のフロールールを全て一旦削除
#それらのフロールールで指定していたMatchにIPアドレス情報(サブネット)を追加
#mitigate時はなんでもPacket-Inするルールは不要なので削除したまま
#mitigate後はなんでもPacket-Inするルールから突っ込んでいく
import logging
import socket
import struct
import ipaddress
#packet_in_handlerにて、受け取ったパケットのipv4がsubnetに属するか調べるのに必要
def is_ipv4_belongs_to_network(ipv4, network):
# netmask -> CIDR
network, netmask = network
network_address = socket.inet_pton(socket.AF_INET, netmask)
cidr_value = bin(struct.unpack('!L', network_address)[0])[2:].index('0')
cidr = "{network}/{cidr_value}".format(**locals())
#check
ipv4 = ipaddress.ip_address(ipv4)
ipv4_network = ipaddress.ip_network(cidr.decode("utf-8"))
return ipv4 in ipv4_network
|
tukeJonny/NTPAmpMitigator
|
infra/utils.py
|
Python
|
mit
| 960
|
from sklearn.utils import resample
from darts.api.dataset import Subset
def dummy_indices(dataset):
""" Get indexes for the dataset """
return [x for x in range(len(dataset))]
def sample(dataset, num_samples, replace=True):
""" Sample the dataset """
data_idx = dummy_indices(dataset)
sample_idx = resample(data_idx, n_samples=num_samples, replace=replace)
return Subset(dataset, sample_idx)
|
ECP-CANDLE/Benchmarks
|
common/darts/datasets/sample.py
|
Python
|
mit
| 420
|
__author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota)
|
Meemaw/Eulers-Project
|
Problem_37.py
|
Python
|
mit
| 888
|
import subprocess
from pkg_resources import resource_filename
def playit(file):
"""
Function used to play a sound file
"""
filepath = resource_filename(__name__, 'sound/' + file)
subprocess.Popen(["paplay", filepath])
|
lapisdecor/bzoinq
|
bzoinq/playit.py
|
Python
|
mit
| 240
|
from os import getenv
from time import time, sleep
from core import Platform, Instance
from SoftLayer import Client
from SoftLayer.CCI import CCIManager
from paramiko import SSHClient
class _SuppressPolicy(object):
def missing_host_key(self, client, hostname, key):
pass
class CCIPlatform(Platform):
_required_opts = ['cores', 'memory', 'domain',
'datacenter', 'os_code']
def _on_init(self):
self._client = Client(username=getenv('SL_USERNAME'),
api_key=getenv('SL_API_KEY'))
self._manager = CCIManager(self._client)
def find_instance(self, host_name):
instance = None
host_name = host_name.lower()
for ii in self._manager.list_instances():
fqdn = ii.get('fullyQualifiedDomainName', '')
if fqdn.lower() == host_name:
instance = Instance(id=ii.get('id'), name=fqdn)
break
return instance
def get_instance(self, id):
cci = self._manager.get_instance(id)
return self._cci_to_instance(cci)
def create_instance(self, host_name):
host_bits = host_name.split('.', 1)
host_name = host_bits[0]
domain = host_bits[1] if len(host_bits) >= 2 else self.config('domain')
base_options = {'cpus': self.config('cores'),
'memory': self.config('memory'),
'hostname': host_name,
'domain': domain,
'datacenter': self.config('datacenter'),
'os_code': self.config('os_code')}
print 'creating cci %s/%s' % (host_name, domain)
print base_options
cci = self._manager.create_instance(**base_options)
cci = self._cci_await_ready(cci)
self._cci_install_keys(cci['id'])
return self._cci_to_instance(cci)
def reimage_instance(self, instance):
self._manager.reload_instance(instance.id)
cci = self._manager.get_instance(instance.id)
cci = self._cci_await_transaction_start(cci)
cci = self._cci_await_ready(cci)
self._cci_install_keys(cci['id'])
return self._cci_to_instance(cci)
def delete_instance(self, instance):
self._manager.cancel_instance(instance.id)
self._cci_await_delete(self._manager.get_instance(instance.id))
def instance_ready(self, instance):
cci = self._manager.get_instance(instance.id)
return (cci and 'activeTransaction' not in cci)
def _cci_to_instance(self, cci):
if not cci:
return None
return Instance(id=cci['id'], name=cci['fullyQualifiedDomainName'])
def _cci_await_state(self, cci, state_check, sleep_secs=5):
wait_start = time()
self.log_info('Waiting for %s to change state...' % (cci['id']))
while state_check(cci):
sleep(sleep_secs)
cci = self._manager.get_instance(cci['id'])
self.log_info('...')
self.log_info('Available after %0.3f secs.' % (time() - wait_start))
return cci
def _cci_await_ready(self, cci):
return self._cci_await_state(cci,
lambda c: 'activeTransaction' in c,
sleep_secs=5)
def _cci_await_transaction_start(self, cci):
return self._cci_await_state(cci,
lambda c: 'activeTransaction' not in c,
sleep_secs=2)
def _cci_await_delete(self, cci):
return self._cci_await_state(cci,
lambda c: c and 'id' in c,
sleep_secs=2)
def _get_cci_root_password(self, cci):
passwords = self._manager.get_instance_passwords(cci['id'])
password = None
for p in passwords:
if 'username' in p and p['username'] == 'root':
password = p['password']
break
return password
def _cci_install_keys(self, id):
cci = self._manager.get_instance(id)
password = self._get_cci_root_password(cci)
if not password:
raise Exception('Passwords are not available for instance %s' %
cci['id'])
keys_url = self.config('ssh_key_url')
if not keys_url:
return
client_settings = {'hostname': cci['primaryIpAddress'],
'username': 'root',
'password': password}
client = SSHClient()
client.set_missing_host_key_policy(_SuppressPolicy())
client.connect(look_for_keys=False, **client_settings)
client.exec_command('mkdir -p ~/.ssh')
client.exec_command('wget -T 10 -q -O ~/.ssh/authorized_keys %s' %
keys_url)
client.close()
|
softlayer/stack-dev-tools
|
platforms/softlayer.py
|
Python
|
mit
| 4,908
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "news_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
julienawilson/news-project
|
news_project/manage.py
|
Python
|
mit
| 810
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) The University of Strathclyde 2019
# Author: Leighton Pritchard
#
# Contact:
# leighton.pritchard@strath.ac.uk
#
# Leighton Pritchard,
# Strathclyde Institute of Pharmaceutical and Biomedical Sciences
# The University of Strathclyde
# Cathedral Street
# Glasgow
# G1 1XQ
# Scotland,
# UK
#
# The MIT License
#
# (c) The University of Strathclyde 2019
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Code to implement Seaborn graphics output for ANI analyses."""
import warnings
import matplotlib # pylint: disable=C0411
import pandas as pd
import seaborn as sns
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402,E501 # pylint: disable=wrong-import-position,wrong-import-order,ungrouped-imports
# Add classes colorbar to Seaborn plot
def get_colorbar(dfr, classes):
"""Return a colorbar representing classes, for a Seaborn plot.
:param dfr:
:param classes:
The aim is to get a pd.Series for the passed dataframe columns,
in the form:
0 colour for class in col 0
1 colour for class in col 1
... colour for class in col ...
n colour for class in col n
"""
levels = sorted(list(set(classes.values())))
paldict = dict(
zip(
levels,
sns.cubehelix_palette(
len(levels), light=0.9, dark=0.1, reverse=True, start=1, rot=-2
),
)
)
lvl_pal = {cls: paldict[lvl] for (cls, lvl) in list(classes.items())}
# Have to use string conversion of the dataframe index, here
col_cb = pd.Series([str(_) for _ in dfr.index]).map(lvl_pal)
# The col_cb Series index now has to match the dfr.index, but
# we don't create the Series with this (and if we try, it
# fails) - so change it with this line
col_cb.index = dfr.index
return col_cb
# Add labels to the seaborn heatmap axes
def add_labels(fig, params):
"""Add labels to Seaborn heatmap axes, in-place.
:param fig:
:param params:
"""
if params.labels:
# If a label mapping is missing, use the key text as fall back
for _ in fig.ax_heatmap.get_yticklabels():
_.set_text(params.labels.get(_.get_text(), _.get_text()))
for _ in fig.ax_heatmap.get_xticklabels():
_.set_text(params.labels.get(_.get_text(), _.get_text()))
fig.ax_heatmap.set_xticklabels(fig.ax_heatmap.get_xticklabels(), rotation=90)
fig.ax_heatmap.set_yticklabels(fig.ax_heatmap.get_yticklabels(), rotation=0)
return fig
# Return a clustermap
def get_clustermap(dfr, params, title=None, annot=True):
"""Return a Seaborn clustermap for the passed dataframe.
:param dfr:
:param params:
:param title: str, plot title
:param annot: Boolean, add text for cell values?
"""
# If we do not catch warnings here, then we often get the following warning:
# ClusterWarning: scipy.cluster: The symmetric non-negative hollow
# observation matrix looks suspiciously like an uncondensed distance matrix
# The usual solution would be to convert the array with
# scipy.spatial.distance.squareform(), but this requires that all values in
# the main diagonal are zero, which is not the case for ANI.
# As we know this is a (1-distance) matrix, we could just set the diagonal
# to zero and fudge it, but this is not a good solution. Instead, we suppress
# the warning in a context manager for this function call only, because we
# know the warning is not relevant.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message=(
"scipy.cluster: The symmetric non-negative "
"hollow observation matrix looks suspiciously like an "
"uncondensed distance matrix"
),
)
fig = sns.clustermap(
dfr,
cmap=params.cmap,
vmin=params.vmin,
vmax=params.vmax,
col_colors=params.colorbar,
row_colors=params.colorbar,
figsize=(params.figsize, params.figsize),
linewidths=params.linewidths,
annot=annot,
)
# add labels for each of the input genomes
add_labels(fig, params)
fig.cax.yaxis.set_label_position("left")
if title:
fig.cax.set_ylabel(title)
# Return clustermap
return fig
# Generate Seaborn heatmap output
def heatmap(dfr, outfilename=None, title=None, params=None):
"""Return seaborn heatmap with cluster dendrograms.
:param dfr: pandas DataFrame with relevant data
:param outfilename: path to output file (indicates output format)
:param title:
:param params:
"""
# Decide on figure layout size: a minimum size is required for
# aesthetics, and a maximum to avoid core dumps on rendering.
# If we hit the maximum size, we should modify font size.
maxfigsize = 120
calcfigsize = dfr.shape[0] * 1.1
figsize = min(max(8, calcfigsize), maxfigsize)
if figsize == maxfigsize:
scale = maxfigsize / calcfigsize
sns.set_context("notebook", font_scale=scale)
# Add a colorbar?
if params.classes is None:
col_cb = None
else:
col_cb = get_colorbar(dfr, params.classes)
# Add attributes to parameter object, and draw heatmap
params.colorbar = col_cb
params.figsize = figsize
params.linewidths = 0.25
fig = get_clustermap(dfr, params, title=title)
# Save to file
if outfilename:
fig.savefig(outfilename)
# Return clustermap
return fig
def distribution(dfr, outfilename, matname, title=None):
"""Return seaborn distribution plot for matrix.
:param drf: DataFrame with results matrix
:param outfilename: Path to output file for writing
:param matname: str, type of matrix being plotted
:param title: str, optional title
"""
fill = "#A6C8E0"
rug = "#2678B2"
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
fig.suptitle(title)
sns.histplot(
dfr.values.flatten(),
ax=axes[0],
stat="count",
element="step",
color=fill,
edgecolor=fill,
)
axes[0].set_ylim(ymin=0)
sns.kdeplot(dfr.values.flatten(), ax=axes[1])
sns.rugplot(dfr.values.flatten(), ax=axes[1], color=rug)
# Modify axes after data is plotted
for _ in axes:
if matname == "sim_errors":
_.set_xlim(0, _.get_xlim()[1])
elif matname in ["hadamard", "coverage"]:
_.set_xlim(0, 1.01)
elif matname == "identity":
_.set_xlim(0.75, 1.01)
# Tidy figure
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
if outfilename:
# For some reason seaborn gives us an AxesSubPlot with
# sns.distplot, rather than a Figure, so we need this hack
fig.savefig(outfilename)
return fig
def scatter(
dfr1,
dfr2,
outfilename=None,
matname1="identity",
matname2="coverage",
title=None,
params=None,
):
"""Return seaborn scatterplot.
:param dfr1: pandas DataFrame with x-axis data
:param dfr2: pandas DataFrame with y-axis data
:param outfilename: path to output file (indicates output format)
:param matname1: name of x-axis data
:param matname2: name of y-axis data
:param title: title for the plot
:param params: a list of parameters for plotting: [colormap, vmin, vmax]
"""
# Make an empty dataframe to collect the input data in
combined = pd.DataFrame()
# Add data
combined[matname1] = dfr1.values.flatten()
combined[matname2] = dfr2.values.flatten()
# Add lable information, if available
# if params.labels:
# hue = "labels"
# combined['labels'] = # add labels to dataframe; unsure of their configuration at this point
# else:
hue = None
# Create the plot
fig = sns.lmplot(
x=matname1,
y=matname2,
data=combined,
hue=hue,
fit_reg=False,
scatter_kws={"s": 2},
)
fig.set(xlabel=matname1.title(), ylabel=matname2.title())
plt.title(title)
# Save to file
if outfilename:
fig.savefig(outfilename)
# Return clustermap
return fig
|
widdowquinn/pyani
|
pyani/pyani_graphics/sns/__init__.py
|
Python
|
mit
| 9,274
|
"""goto_cloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
jdepoix/goto_cloud
|
goto_cloud/urls.py
|
Python
|
mit
| 767
|
from __future__ import with_statement
import sys
from collections import deque
from charpos import CharposStream
from bindings import bindings
import printervars
__all__ = ["PrettyPrinter", "pprint"]
class PrintLevelExceeded(StopIteration):
pass
class Token(object):
"""Base class for prettyprinter tokens.
Token instances should not be created directly by the user; the
corresponding PrettyPrinter methods should be used instead."""
size = 0
def output(self, pp):
"""Send output to the given PrettyPrinter stream.
These methods collectively correspond to Oppen's `print' routine."""
pass
class Begin(Token):
"""Begin a logical block."""
def __init__(self, prefix="", per_line=False):
self.prefix = prefix
self.per_line = per_line
def output(self, pp):
offset = pp.charpos
if self.prefix:
pp._write(self.prefix)
if self.per_line:
# Following XP, per-line prefixes are arranged to print directly
# below the occurrence of the prefix on the first line.
pp.prefix += (offset - len(pp.prefix)) * " " + self.prefix
pp.printstack.append((pp.prefix,
pp.space,
pp.charpos - len(pp.prefix),
self.size <= pp.space))
class End(Token):
"""End a logical block."""
def __init__(self, suffix=""):
self.suffix = suffix
def output(self, pp):
if self.suffix:
pp._write(self.suffix)
try:
pp.printstack.pop()
pp.prefix = pp.printstack[-1][0] if pp.printstack else ""
except IndexError:
pass
class Newline(Token):
"""Base class for conditional newlines."""
def indent(self, pp, n):
"""Break the current line and indent to column n."""
pp.blankspace = "" # suppress trailing whitespace
pp.terpri()
pp._write(" " * n)
class Linear(Newline):
def output(self, pp):
(offset, fits) = pp.printstack[-1][-2:]
if not fits:
self.indent(pp, offset)
class Fill(Newline):
def output(self, pp):
(offset, fits) = pp.printstack[-1][-2:]
if not fits and self.size > pp.space:
self.indent(pp, offset)
class Mandatory(Newline):
def output(self, pp):
self.indent(pp, pp.printstack[-1][-2])
class Indentation(Token):
def __init__(self, offset=0, relative=False):
self.offset = offset
self.relative = relative
def output(self, pp):
(prefix, space, offset, fits) = pp.printstack.pop()
offset = pp.margin - ((pp.space if self.relative else space) + \
len(prefix) - self.offset)
pp.printstack.append((prefix, space, offset, fits))
class String(Token):
def __init__(self, string, size):
self.string = string
self.size = size
def output(self, pp):
pp._write(self.string)
class LogicalBlock(object):
"""A context manager for logical blocks."""
def __init__(self, pp, lst, *args, **kwargs):
self.pp = pp
self.list = lst and list(lst)
self.len = len(self.list) if lst else 0
self.suffix = kwargs.pop("suffix", "")
self.args = args
self.kwargs = kwargs
self.print_level_exceeded = None
def __enter__(self):
try:
self.pp.begin(*self.args, **self.kwargs)
except PrintLevelExceeded, e:
self.pp.write("#")
self.print_level_exceeded = e
return iter([])
self.index = 0
return self
def __exit__(self, type, value, traceback):
if not self.print_level_exceeded:
self.pp.end(suffix=self.suffix)
return type and issubclass(type, StopIteration)
def __iter__(self):
return self
def next(self):
if self.index == self.len:
raise StopIteration
elif self.index == printervars.print_length:
self.pp.write("...")
raise StopIteration
value = self.list[self.index]
self.index += 1
return value
def exit_if_list_exhausted(self):
if self.index == self.len:
raise StopIteration
class PrettyPrinter(CharposStream):
def __init__(self, stream=sys.stdout, width=None, charpos=None):
"""Pretty-print to stream, with right margin at width characters,
starting at position charpos."""
if not stream:
raise RuntimeError("pretty-printing to nowhere")
self.stream = stream
self.closed = False
self.margin = self.output_width if width is None else int(width)
if self.margin <= 0:
raise ValueError("margin must be positive")
if charpos is None:
try:
charpos = stream.charpos
except AttributeError:
charpos = 0
self.space = self.margin - charpos
self.scanstack = deque()
self.printstack = list()
self.queue = list()
self.blankspace = "" # trailing whitespace
self.prefix = "" # per-line prefix
self.level = 0 # depth counter
def write(self, string):
"""Enqueue a string for output."""
assert not self.closed, "I/O operation on closed stream"
if not self.scanstack:
self._write(string)
else:
l = len(string)
q = self.queue[-1]
if isinstance(q, String):
# Don't create a seperate token; merge with the last one.
q.string += string
q.size += l
else:
self.queue.append(String(string, l))
self.rightotal += l
while self.rightotal - self.leftotal > self.space:
self.scanstack.popleft().size = 999999 # infinity
self.flush()
def begin(self, *args, **kwargs):
"""Begin a new logical block."""
assert not self.closed, "I/O operation on closed stream"
if printervars.print_level is not None and \
self.level >= printervars.print_level:
raise PrintLevelExceeded(self.level)
if not self.scanstack:
self.leftotal = self.rightotal = 1
assert not self.queue, "queue should be empty"
tok = Begin(*args, **kwargs)
tok.size = -self.rightotal
self.queue.append(tok)
self.rightotal += len(tok.prefix)
self.scanstack.append(tok)
self.level += 1
def end(self, *args, **kwargs):
"""End the current logical block."""
assert not self.closed, "I/O operation on closed stream"
tok = End(*args, **kwargs)
if not self.scanstack:
tok.output(self)
else:
self.level -= 1
self.queue.append(tok)
self.rightotal += len(tok.suffix)
top = self.scanstack.pop()
top.size += self.rightotal
if isinstance(top, Newline) and self.scanstack:
top = self.scanstack.pop()
top.size += self.rightotal
if not self.scanstack:
self.flush()
def newline(self, fill=False, mandatory=False):
"""Enqueue a conditional newline."""
assert not self.closed, "I/O operation on closed stream"
replace = False
if not self.scanstack:
self.leftotal = self.rightotal = 1
assert not self.queue, "queue should be empty"
else:
top = self.scanstack[-1]
if isinstance(top, Newline):
top.size += self.rightotal
replace = True
tok = Mandatory() if mandatory \
else Fill() if fill \
else Linear()
tok.size = -self.rightotal
if replace:
self.scanstack[-1] = tok
else:
self.scanstack.append(tok)
self.queue.append(tok)
def indent(self, *args, **kwargs):
"""Set the indentation level for the current logical block."""
assert not self.closed, "I/O operation on closed stream"
self.queue.append(Indentation(*args, **kwargs))
def logical_block(self, lst=None, *args, **kwargs):
"""Return a context manager for a new logical block."""
assert not self.closed, "I/O operation on closed stream"
return LogicalBlock(self, lst, *args, **kwargs)
def pprint(self, obj):
"""Pretty-print the given object."""
def inflection(obj):
if isinstance(obj, list):
return ("[", "]")
else:
return ("%s([" % type(obj).__name__, "])")
assert not self.closed, "I/O operation on closed stream"
if isinstance(obj, basestring):
self.write(repr(obj) if printervars.print_escape and \
obj not in ("\n", "\t") \
else obj)
elif isinstance(obj, (int, float, long, complex)):
self.write(repr(obj) if printervars.print_escape else str(obj))
elif isinstance(obj, (list, set, frozenset, deque)):
(prefix, suffix) = inflection(obj)
with self.logical_block(obj, prefix=prefix, suffix=suffix) as l:
for x in l:
self.pprint(x)
l.exit_if_list_exhausted()
self.write(", ")
if printervars.print_pretty:
self.newline(fill=True)
elif isinstance(obj, tuple):
with self.logical_block(obj, prefix="(", suffix=")") as l:
x = l.next()
self.pprint(x)
self.write(",")
l.exit_if_list_exhausted()
self.write(" ")
if printervars.print_pretty:
self.newline(fill=True)
for x in l:
self.pprint(x)
l.exit_if_list_exhausted()
self.write(", ")
if printervars.print_pretty:
self.newline(fill=True)
elif isinstance(obj, dict):
with self.logical_block(obj.iteritems(),
prefix="{", suffix="}") as l:
for (key, value) in l:
self.pprint(key)
self.write(": ")
self.pprint(value)
l.exit_if_list_exhausted()
self.write(", ")
if printervars.print_pretty:
self.newline(fill=True)
elif printervars.print_pretty and hasattr(obj, "__pprint__"):
obj.__pprint__(self)
else:
self.write(repr(obj) if printervars.print_escape else str(obj))
def flush(self):
"""Output as many queue entries as possible."""
assert not self.closed, "I/O operation on closed stream"
queue = self.queue
i = 0
total = 0
for q in queue:
if q.size < 0:
break
q.output(self)
total += q.size
i += 1
if i > 0:
self.queue = queue[i:]
self.leftotal += total
def close(self):
if not self.closed:
self.flush()
assert not self.queue, "leftover items in output queue"
assert not self.scanstack, "leftover itmes on scan stack"
assert not self.printstack, "leftover items on print stack"
self.closed = True
def terpri(self):
assert not self.closed, "I/O operation on closed stream"
self.stream.write(self.blankspace + "\n" + self.prefix)
self.blankspace = ""
self.space = self.margin - len(self.prefix)
def _write(self, str):
"""Write the given string to the underlying stream."""
# There are two sources of trickiness here: the fact that per-line
# prefixes need to be printed on every line, no matter how the
# newline occurs, and the trailing whitespace suppression.
# The former is handled by breaking the string at newlines and
# letting terpri take care of printing the prefix. The latter
# involves not immediately printing any trailing whitespace, but
# keeping it around and ensuring that it is eventually printed,
# unless explicitly suppressed (as is done by the conditional newline
# output methods). Note that we *count* trailing whitespace here
# as if it had been printed (in adjusting self.space); this is
# needed for things that depend on charpos to work correctly
# (e.g., indentation).
(before, newline, after) = str.partition("\n")
if newline:
self.stream.write(self.blankspace + before)
self.blankspace = ""
self.terpri()
self._write(after)
else:
i = n = len(before)
while i > 0 and before[i-1] == " ":
i -= 1
self.stream.write(self.blankspace + before[:i])
self.blankspace = before[i:]
self.space -= n
@property
def charpos(self):
return self.margin - self.space
def pprint(obj, *args, **kwargs):
pp = PrettyPrinter(*args, **kwargs)
with bindings(printervars, print_pretty=True):
pp.pprint(obj)
pp.terpri()
pp.close()
|
plotnick/prettyprinter
|
prettyprinter.py
|
Python
|
mit
| 13,549
|
from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Course.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_POST
def addCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.addCourseCurriculum(request.POST)
except Exception as e:
response_data['success'] = '0'
response_data['exception'] = str(e)
else:
response_data['success'] = '1'
data = serializers.serialize('json', [C, ])
response_data["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_POST
def editCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.editCourseCurriculum(request.POST)
except Exception as e:
response_data['success'] = '0'
response_data['exception'] = str(e)
else:
response_data['success'] = '1'
data = serializers.serialize('json', [C, ])
response_data["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_POST
def deleteCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.deleteCourseCurriculum(request.POST)
except Exception as e:
response_data['success'] = '0'
response_data['exception'] = str(e)
else:
response_data['success'] = '1'
data = serializers.serialize('json', [C, ])
response_data["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_GET
def getCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.getCourseCurriculum(request.GET)
except Exception as e:
response_data["success"] = 0
response_data['exception'] = str(e)
else:
response_data["success"] = 1
data = serializers.serialize('json', [C.instructor, ])
response_data["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
@csrf_exempt
@require_GET
def retrieveCourseCurriculum(request):
response_data = {}
try:
C = CourseCurriculum.objects.retrieveCourseCurriculum(request.GET)
except Exception as e:
response_data['success'] = '0'
response_data['exception'] = str(e)
else:
response_data['success'] = '1'
global data
try:
data = serializers.serialize('json', C)
except Exception as e:
data = serializers.serialize('json', [C, ])
response_data["coursecurriculum"] = json.loads(data)
return JsonResponse(response_data)
|
IEEEDTU/CMS
|
Course/views/CourseCurriculum.py
|
Python
|
mit
| 2,775
|
import logging
import requests
import slacksocket.errors as errors
log = logging.getLogger('slacksocket')
class WebClient(requests.Session):
""" Minimal client for connecting to Slack web API """
def __init__(self, token):
self._token = token
super(WebClient, self).__init__()
def get(self, url, method='GET', max_attempts=3, **params):
if max_attempts == 0:
raise errors.SlackAPIError('Max retries exceeded')
elif max_attempts < 0:
message = 'Expected max_attempts >= 0, got {0}'\
.format(max_attempts)
raise ValueError(message)
params['token'] = self._token
res = self.request(method, url, params=params)
try:
res.raise_for_status()
except requests.exceptions.HTTPError as e:
raise errors.SlackAPIError(e)
rj = res.json()
if rj['ok']:
return rj
# process error
if rj['error'] == 'migration_in_progress':
log.info('socket in migration state, retrying')
time.sleep(2)
return self.get(url,
method=method,
max_attempts=max_attempts - 1,
**params)
else:
raise errors.SlackAPIError('Error from slack api:\n%s' % res.text)
|
graywizardx/slacksocket
|
slacksocket/webclient.py
|
Python
|
mit
| 1,363
|
'''Tests for the ValidateHash object'''
from __future__ import absolute_import
import unittest
from nose.tools import assert_true, assert_false
from hashit.core.hash_data import HashData
from hashit.core.hash_type import HashType
from hashit.service.validate_hash import ValidateHash
from hashit.utils.data_encap import DataEncap
from hashit.utils.data_type import DataType
# pylint: disable=missing-docstring
# pylint: disable=invalid-name
# pylint: disable=no-self-use
class TestHashIt(unittest.TestCase):
def setUp(self):
self.data = HashData(
DataEncap(DataType.FILE, "test/support/example.bin"))
def tearDown(self):
pass
def test_verify_hash_crc8_expected_result(self):
assert_true(ValidateHash(
result="14",
hash_type=HashType.CRC8,
data=self.data
).is_vaild())
def test_verify_hash_crc8_bad_result(self):
assert_false(ValidateHash(
result="FE",
hash_type=HashType.CRC8,
data=self.data
).is_vaild())
def test_verify_hash_crc16_expected_result(self):
assert_true(ValidateHash(
result="BAD3",
hash_type=HashType.CRC16,
data=self.data
).is_vaild())
def test_verify_hash_crc16_bad_result(self):
assert_false(ValidateHash(
result="78E7",
hash_type=HashType.CRC16,
data=self.data
).is_vaild())
def test_verify_hash_crc32_expected_result(self):
assert_true(ValidateHash(
result="29058C73",
hash_type=HashType.CRC32,
data=self.data
).is_vaild())
def test_verify_hash_crc32_bad_result(self):
assert_false(ValidateHash(
result="ACEF2345",
hash_type=HashType.CRC32,
data=self.data
).is_vaild())
def test_verify_hash_crc64_expected_result(self):
assert_true(ValidateHash(
result="6C27EAA78BA3F822",
hash_type=HashType.CRC64,
data=self.data
).is_vaild())
def test_verify_hash_crc64_bad_result(self):
assert_false(ValidateHash(
result="DEADBEEFF00DB00F",
hash_type=HashType.CRC64,
data=self.data
).is_vaild())
def test_verify_hash_md5_expected_result(self):
assert_true(ValidateHash(
result="E2C865DB4162BED963BFAA9EF6AC18F0",
hash_type=HashType.MD5,
data=self.data
).is_vaild())
def test_verify_hash_md5_bad_result(self):
assert_false(ValidateHash(
result="11223344556677889900AECF431304065",
hash_type=HashType.MD5,
data=self.data
).is_vaild())
def test_verify_hash_sha1_expected_result(self):
assert_true(ValidateHash(
result="4916D6BDB7F78E6803698CAB32D1586EA457DFC8",
hash_type=HashType.SHA1,
data=self.data
).is_vaild())
def test_verify_hash_sha1_bad_result(self):
assert_false(ValidateHash(
result="987654321AC12345876543BCC34567862737FF20",
hash_type=HashType.SHA1,
data=self.data
).is_vaild())
def test_verify_hash_sha224_expected_result(self):
assert_true(ValidateHash(
result="88702E63237824C4EB0D0FCFE41469A462493E8BEB2A75BBE5981734",
hash_type=HashType.SHA224,
data=self.data
).is_vaild())
def test_verify_hash_sha224_bad_result(self):
assert_false(ValidateHash(
result="AACCEEDDFF928173647D0FBC09375847268EB88EEFF378592047583",
hash_type=HashType.SHA224,
data=self.data
).is_vaild())
def test_verify_hash_sha256_expected_result(self):
assert_true(ValidateHash(
result="40AFF2E9D2D8922E47AFD4648E6967497158785FBD1DA870E7110266BF944880",
hash_type=HashType.SHA256,
data=self.data
).is_vaild())
def test_verify_hash_sha256_bad_result(self):
assert_false(ValidateHash(
result="AF82E982D8922E47AFD4648E674ACE587BEEF85FBD1D0266BF944880123455FF",
hash_type=HashType.SHA256,
data=self.data
).is_vaild())
|
art-of-dom/hash-it
|
test/test_validate_hash.py
|
Python
|
mit
| 4,257
|
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# -*- mode: python; indent-tabs-mode nil; tab-width 4; python-indent 4; -*-
"""
usage: gidget add data <filename>
gidget add reference <filename>
"""
from docopt import docopt
if __name__ == '__main__':
print(docopt(__doc__))
|
cancerregulome/gidget
|
gidget/gidget_add.py
|
Python
|
mit
| 300
|
# coding=utf-8
from re import match
from mapi.exceptions import (
MapiNetworkException,
MapiNotFoundException,
MapiProviderException,
)
from mapi.utils import clean_dict, request_json
__all__ = [
"omdb_search",
"omdb_title",
"tmdb_find",
"tmdb_movies",
"tmdb_search_movies",
"tvdb_episodes_id",
"tvdb_login",
"tvdb_refresh_token",
"tvdb_search_series",
"tvdb_series_id",
"tvdb_series_id_episodes",
"tvdb_series_id_episodes_query",
]
OMDB_MEDIA_TYPES = {"episode", "movie", "series"}
OMDB_PLOT_TYPES = {"short", "long"}
TVDB_LANGUAGE_CODES = [
"cs",
"da",
"de",
"el",
"en",
"es",
"fi",
"fr",
"he",
"hr",
"hu",
"it",
"ja",
"ko",
"nl",
"no",
"pl",
"pt",
"ru",
"sl",
"sv",
"tr",
"zh",
]
def omdb_title(
api_key,
id_imdb=None,
media_type=None,
title=None,
season=None,
episode=None,
year=None,
plot=None,
cache=True,
):
"""
Lookup media using the Open Movie Database.
Online docs: http://www.omdbapi.com/#parameters
"""
if (not title and not id_imdb) or (title and id_imdb):
raise MapiProviderException("either id_imdb or title must be specified")
elif media_type and media_type not in OMDB_MEDIA_TYPES:
raise MapiProviderException(
"media_type must be one of %s" % ",".join(OMDB_MEDIA_TYPES)
)
elif plot and plot not in OMDB_PLOT_TYPES:
raise MapiProviderException(
"plot must be one of %s" % ",".join(OMDB_PLOT_TYPES)
)
url = "http://www.omdbapi.com"
parameters = {
"apikey": api_key,
"i": id_imdb,
"t": title,
"y": year,
"season": season,
"episode": episode,
"type": media_type,
"plot": plot,
}
parameters = clean_dict(parameters)
status, content = request_json(url, parameters, cache=cache)
error = content.get("Error") if isinstance(content, dict) else None
if status == 401:
raise MapiProviderException("invalid API key")
elif status != 200 or not isinstance(content, dict):
raise MapiNetworkException("OMDb down or unavailable?")
elif error:
raise MapiNotFoundException(error)
return content
def omdb_search(api_key, query, year=None, media_type=None, page=1, cache=True):
"""
Search for media using the Open Movie Database.
Online docs: http://www.omdbapi.com/#parameters.
"""
if media_type and media_type not in OMDB_MEDIA_TYPES:
raise MapiProviderException(
"media_type must be one of %s" % ",".join(OMDB_MEDIA_TYPES)
)
if 1 > page > 100:
raise MapiProviderException("page must be between 1 and 100")
url = "http://www.omdbapi.com"
parameters = {
"apikey": api_key,
"s": query,
"y": year,
"type": media_type,
"page": page,
}
parameters = clean_dict(parameters)
status, content = request_json(url, parameters, cache=cache)
if status == 401:
raise MapiProviderException("invalid API key")
elif content and not content.get("totalResults"):
raise MapiNotFoundException()
elif not content or status != 200: # pragma: no cover
raise MapiNetworkException("OMDb down or unavailable?")
return content
def tmdb_find(
api_key, external_source, external_id, language="en-US", cache=True
):
"""
Search for The Movie Database objects using another DB's foreign key.
Note: language codes aren't checked on this end or by TMDb, so if you
enter an invalid language code your search itself will succeed, but
certain fields like synopsis will just be empty.
Online docs: developers.themoviedb.org/3/find.
"""
sources = ["imdb_id", "freebase_mid", "freebase_id", "tvdb_id", "tvrage_id"]
if external_source not in sources:
raise MapiProviderException("external_source must be in %s" % sources)
if external_source == "imdb_id" and not match(r"tt\d+", external_id):
raise MapiProviderException("invalid imdb tt-const value")
url = "https://api.themoviedb.org/3/find/" + external_id or ""
parameters = {
"api_key": api_key,
"external_source": external_source,
"language": language,
}
keys = [
"movie_results",
"person_results",
"tv_episode_results",
"tv_results",
"tv_season_results",
]
status, content = request_json(url, parameters, cache=cache)
if status == 401:
raise MapiProviderException("invalid API key")
elif status != 200 or not any(content.keys()): # pragma: no cover
raise MapiNetworkException("TMDb down or unavailable?")
elif status == 404 or not any(content.get(k, {}) for k in keys):
raise MapiNotFoundException
return content
def tmdb_movies(api_key, id_tmdb, language="en-US", cache=True):
"""
Lookup a movie item using The Movie Database.
Online docs: developers.themoviedb.org/3/movies.
"""
try:
url = "https://api.themoviedb.org/3/movie/%d" % int(id_tmdb)
except ValueError:
raise MapiProviderException("id_tmdb must be numeric")
parameters = {"api_key": api_key, "language": language}
status, content = request_json(url, parameters, cache=cache)
if status == 401:
raise MapiProviderException("invalid API key")
elif status == 404:
raise MapiNotFoundException
elif status != 200 or not any(content.keys()): # pragma: no cover
raise MapiNetworkException("TMDb down or unavailable?")
return content
def tmdb_search_movies(
api_key, title, year=None, adult=False, region=None, page=1, cache=True
):
"""
Search for movies using The Movie Database.
Online docs: developers.themoviedb.org/3/search/search-movies.
"""
url = "https://api.themoviedb.org/3/search/movie"
try:
if year:
year = int(year)
except ValueError:
raise MapiProviderException("year must be numeric")
parameters = {
"api_key": api_key,
"query": title,
"page": page,
"include_adult": adult,
"region": region,
"year": year,
}
status, content = request_json(url, parameters, cache=cache)
if status == 401:
raise MapiProviderException("invalid API key")
elif status != 200 or not any(content.keys()): # pragma: no cover
raise MapiNetworkException("TMDb down or unavailable?")
elif status == 404 or status == 422 or not content.get("total_results"):
raise MapiNotFoundException
return content
def tvdb_login(api_key):
"""
Logs into TVDb using the provided api key.
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login.
"""
url = "https://api.thetvdb.com/login"
body = {"apikey": api_key}
status, content = request_json(url, body=body, cache=False)
if status == 401:
raise MapiProviderException("invalid api key")
elif status != 200 or not content.get("token"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content["token"]
def tvdb_refresh_token(token):
"""
Refreshes JWT token.
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token.
"""
url = "https://api.thetvdb.com/refresh_token"
headers = {"Authorization": "Bearer %s" % token}
status, content = request_json(url, headers=headers, cache=False)
if status == 401:
raise MapiProviderException("invalid token")
elif status != 200 or not content.get("token"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content["token"]
def tvdb_episodes_id(token, id_tvdb, lang="en", cache=True):
"""
Returns the full information for a given episode id.
Online docs: https://api.thetvdb.com/swagger#!/Episodes.
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
"'lang' must be one of %s" % ",".join(TVDB_LANGUAGE_CODES)
)
try:
url = "https://api.thetvdb.com/episodes/%d" % int(id_tvdb)
except ValueError:
raise MapiProviderException("id_tvdb must be numeric")
headers = {"Accept-Language": lang, "Authorization": "Bearer %s" % token}
status, content = request_json(url, headers=headers, cache=cache)
if status == 401:
raise MapiProviderException("invalid token")
elif status == 404:
raise MapiNotFoundException
elif status == 200 and "invalidLanguage" in content.get("errors", {}):
raise MapiNotFoundException
elif status != 200 or not content.get("data"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content
def tvdb_series_id(token, id_tvdb, lang="en", cache=True):
"""
Returns a series records that contains all information known about a
particular series id.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id.
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
"'lang' must be one of %s" % ",".join(TVDB_LANGUAGE_CODES)
)
try:
url = "https://api.thetvdb.com/series/%d" % int(id_tvdb)
except ValueError:
raise MapiProviderException("id_tvdb must be numeric")
headers = {"Accept-Language": lang, "Authorization": "Bearer %s" % token}
status, content = request_json(url, headers=headers, cache=cache)
if status == 401:
raise MapiProviderException("invalid token")
elif status == 404:
raise MapiNotFoundException
elif status != 200 or not content.get("data"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content
def tvdb_series_id_episodes(token, id_tvdb, page=1, lang="en", cache=True):
"""
All episodes for a given series.
Note: Paginated with 100 results per page.
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id_episodes.
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
"'lang' must be one of %s" % ",".join(TVDB_LANGUAGE_CODES)
)
try:
url = "https://api.thetvdb.com/series/%d/episodes" % int(id_tvdb)
except ValueError:
raise MapiProviderException("id_tvdb must be numeric")
headers = {"Accept-Language": lang, "Authorization": "Bearer %s" % token}
parameters = {"page": page}
status, content = request_json(
url, parameters, headers=headers, cache=cache
)
if status == 401:
raise MapiProviderException("invalid token")
elif status == 404:
raise MapiNotFoundException
elif status != 200 or not content.get("data"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content
def tvdb_series_id_episodes_query(
token, id_tvdb, episode=None, season=None, page=1, lang="en", cache=True
):
"""
Allows the user to query against episodes for the given series.
Note: Paginated with 100 results per page; omitted imdbId-- when would you
ever need to query against both tvdb and imdb series ids?
Online docs: api.thetvdb.com/swagger#!/Series/get_series_id_episodes_query.
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
"'lang' must be one of %s" % ",".join(TVDB_LANGUAGE_CODES)
)
try:
url = "https://api.thetvdb.com/series/%d/episodes/query" % int(id_tvdb)
except ValueError:
raise MapiProviderException("id_tvdb must be numeric")
headers = {"Accept-Language": lang, "Authorization": "Bearer %s" % token}
parameters = {"airedSeason": season, "airedEpisode": episode, "page": page}
status, content = request_json(
url, parameters, headers=headers, cache=cache
)
if status == 401:
raise MapiProviderException("invalid token")
elif status == 404:
raise MapiNotFoundException
elif status != 200 or not content.get("data"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content
def tvdb_search_series(
token, series=None, id_imdb=None, id_zap2it=None, lang="en", cache=True
):
"""
Allows the user to search for a series based on the following parameters.
Online docs: https://api.thetvdb.com/swagger#!/Search/get_search_series
Note: results a maximum of 100 entries per page, no option for pagination.
"""
if lang not in TVDB_LANGUAGE_CODES:
raise MapiProviderException(
"'lang' must be one of %s" % ",".join(TVDB_LANGUAGE_CODES)
)
url = "https://api.thetvdb.com/search/series"
parameters = {"name": series, "imdbId": id_imdb, "zap2itId": id_zap2it}
headers = {"Accept-Language": lang, "Authorization": "Bearer %s" % token}
status, content = request_json(
url, parameters, headers=headers, cache=cache
)
if status == 401:
raise MapiProviderException("invalid token")
elif status == 405:
raise MapiProviderException(
"series, id_imdb, id_zap2it parameters are mutually exclusive"
)
elif status == 404: # pragma: no cover
raise MapiNotFoundException
elif status != 200 or not content.get("data"): # pragma: no cover
raise MapiNetworkException("TVDb down or unavailable?")
return content
|
jkwill87/mapi
|
mapi/endpoints.py
|
Python
|
mit
| 13,575
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'CustomUser.email_on_new_foller'
db.delete_column('auth_user', 'email_on_new_foller')
# Adding field 'CustomUser.email_on_new_follower'
db.add_column('auth_user', 'email_on_new_follower',
self.gf('django.db.models.fields.BooleanField')(default=True),
keep_default=False)
def backwards(self, orm):
# Adding field 'CustomUser.email_on_new_foller'
db.add_column('auth_user', 'email_on_new_foller',
self.gf('django.db.models.fields.BooleanField')(default=True),
keep_default=False)
# Deleting field 'CustomUser.email_on_new_follower'
db.delete_column('auth_user', 'email_on_new_follower')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'main.customuser': {
'Meta': {'object_name': 'CustomUser', 'db_table': "'auth_user'"},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'email_on_new_follower': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'main.embeditem': {
'Meta': {'object_name': 'EmbedItem'},
'border_color': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'border_radius': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'border_width': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']", 'null': 'True'}),
'creator_ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'creator_session_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'creator_window_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'embedly_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'original_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Page']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'x': ('django.db.models.fields.IntegerField', [], {}),
'y': ('django.db.models.fields.IntegerField', [], {})
},
u'main.follow': {
'Meta': {'unique_together': "[['user', 'target']]", 'object_name': 'Follow'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'target': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followers'", 'to': u"orm['main.CustomUser']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'friends'", 'to': u"orm['main.CustomUser']"})
},
u'main.imageitem': {
'Meta': {'object_name': 'ImageItem'},
'border_color': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'border_radius': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'border_width': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']", 'null': 'True'}),
'creator_ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'creator_session_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'creator_window_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'link_to_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Page']"}),
'src': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'x': ('django.db.models.fields.IntegerField', [], {}),
'y': ('django.db.models.fields.IntegerField', [], {})
},
u'main.membership': {
'Meta': {'unique_together': "[['page', 'user']]", 'object_name': 'Membership'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Page']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']"})
},
u'main.page': {
'Meta': {'object_name': 'Page'},
'admin_textitem_bg_color': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}),
'admin_textitem_bg_texture': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'admin_textitem_color': ('django.db.models.fields.CharField', [], {'default': "'#000'", 'max_length': '32', 'blank': 'True'}),
'admin_textitem_font': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'admin_textitem_font_size': ('django.db.models.fields.PositiveIntegerField', [], {'default': '13', 'null': 'True', 'blank': 'True'}),
'bg_color': ('django.db.models.fields.CharField', [], {'default': "'#fafafa'", 'max_length': '32', 'blank': 'True'}),
'bg_fn': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'bg_texture': ('django.db.models.fields.CharField', [], {'default': "'light_wool_midalpha.png'", 'max_length': '1024', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'creator_ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'creator_session_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'default_textitem_bg_color': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}),
'default_textitem_bg_texture': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'default_textitem_color': ('django.db.models.fields.CharField', [], {'default': "'#000'", 'max_length': '32', 'blank': 'True'}),
'default_textitem_font': ('django.db.models.fields.CharField', [], {'default': "'Arial'", 'max_length': '32', 'blank': 'True'}),
'default_textitem_font_size': ('django.db.models.fields.PositiveIntegerField', [], {'default': '13', 'null': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'image_writability': ('django.db.models.fields.IntegerField', [], {'default': '3'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']", 'null': 'True', 'blank': 'True'}),
'published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'published_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'short_url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'text_writability': ('django.db.models.fields.IntegerField', [], {'default': '3'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'use_custom_admin_style': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'main.pageview': {
'Meta': {'object_name': 'PageView'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Page']"}),
'sessionid': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']", 'null': 'True'})
},
u'main.textitem': {
'Meta': {'object_name': 'TextItem'},
'bg_color': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'bg_texture': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'border_color': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'border_radius': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'border_width': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'color': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.CustomUser']", 'null': 'True'}),
'creator_ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'creator_session_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'creator_window_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'font': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'font_size': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'primary_key': 'True'}),
'link_to_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Page']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'x': ('django.db.models.fields.IntegerField', [], {}),
'y': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['main']
|
reverie/jotleaf.com
|
jotleaf/main/migrations/0003_auto__del_field_customuser_email_on_new_foller__add_field_customuser_e.py
|
Python
|
mit
| 16,495
|
"""Add user table to support doorman and oauth authentication.
Revision ID: 0bc0a93ac867
Revises: fd28e46e46a6
Create Date: 2016-05-11 11:01:40.472139
"""
# revision identifiers, used by Alembic.
revision = '0bc0a93ac867'
down_revision = 'fd28e46e46a6'
from alembic import op
import sqlalchemy as sa
import doorman.database
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=80), nullable=False),
sa.Column('email', sa.String(), nullable=True),
sa.Column('password', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('social_id', sa.String(), nullable=True),
sa.Column('first_name', sa.String(), nullable=True),
sa.Column('last_name', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
### end Alembic commands ###
|
mwielgoszewski/doorman
|
migrations/versions/0bc0a93ac867_.py
|
Python
|
mit
| 1,141
|
"""This module contains the ``list_user`` command."""
import click
from ovmm.handlers.postgres import PostgreSQLDatabaseHandler
@click.command()
def list_user():
"""List users managed by ovmm."""
click.echo('\n{:-^60}'.format(' Process: List Users '))
postgres = PostgreSQLDatabaseHandler()
user_list = postgres.list_user()
click.echo('List of user names:')
for i in user_list:
click.echo(i)
click.echo('{:-^60}\n'.format(' Process: End '))
|
tobiasraabe/otree_virtual_machine_manager
|
ovmm/commands/list_user.py
|
Python
|
mit
| 484
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. module:: ellipse_fitting
:platform: Unix, Windows
:synopsis: Ellipse fitting algorithms and handling of ellipse information.
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2013-05-05, 23:22
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import numpy as np
from b2ac.compat import *
from b2ac.matrix.matrix_ref import inverse_symmetric_3by3_double, inverse_symmetric_3by3_int, add_symmetric_matrix
def fit_B2AC(points):
"""Ellipse fitting in Python with numerically unstable algorithm.
Described `here <http://research.microsoft.com/pubs/67845/ellipse-pami.pdf>`_.
N_POLYPOINTS.B. Do not use, since it works with almost singular matrix.
:param points: The [Nx2] array of points to fit ellipse to.
:type points: :py:class:`numpy.ndarray`
:return: The conic section array defining the fitted ellipse.
:rtype: :py:class:`numpy.ndarray`
"""
import scipy.linalg as scla
constraint_matrix = np.zeros((6, 6))
constraint_matrix[0, 2] = 2
constraint_matrix[1, 1] = -1
constraint_matrix[2, 0] = 2
S = _calculate_scatter_matrix_py(points[:, 0], points[:, 1])
evals, evect = scla.eig(S, constraint_matrix)
ind = np.where(evals == (evals[evals > 0].min()))[0][0]
return evect[:, ind]
def fit_improved_B2AC_numpy(points):
"""Ellipse fitting in Python with improved B2AC algorithm as described in
this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_.
This version of the fitting simply applies NumPy:s methods for calculating
the conic section, modelled after the Matlab code in the paper:
.. code-block::
function a = fit_ellipse(x, y)
D1 = [x .ˆ 2, x .* y, y .ˆ 2]; % quadratic part of the design matrix
D2 = [x, y, ones(size(x))]; % linear part of the design matrix
S1 = D1’ * D1; % quadratic part of the scatter matrix
S2 = D1’ * D2; % combined part of the scatter matrix
S3 = D2’ * D2; % linear part of the scatter matrix
T = - inv(S3) * S2’; % for getting a2 from a1
M = S1 + S2 * T; % reduced scatter matrix
M = [M(3, :) ./ 2; - M(2, :); M(1, :) ./ 2]; % premultiply by inv(C1)
[evec, eval] = eig(M); % solve eigensystem
cond = 4 * evec(1, :) .* evec(3, :) - evec(2, :) .ˆ 2; % evaluate a’Ca
a1 = evec(:, find(cond > 0)); % eigenvector for min. pos. eigenvalue
a = [a1; T * a1]; % ellipse coefficients
:param points: The [Nx2] array of points to fit ellipse to.
:type points: :py:class:`numpy.ndarray`
:return: The conic section array defining the fitted ellipse.
:rtype: :py:class:`numpy.ndarray`
"""
x = points[:, 0]
y = points[:, 1]
D1 = np.vstack([x ** 2, x * y, y ** 2]).T
D2 = np.vstack([x, y, np.ones((len(x), ), dtype=x.dtype)]).T
S1 = D1.T.dot(D1)
S2 = D1.T.dot(D2)
S3 = D2.T.dot(D2)
T = -np.linalg.inv(S3).dot(S2.T)
M = S1 + S2.dot(T)
M = np.array([M[2, :] / 2, -M[1, :], M[0, :] / 2])
eval, evec = np.linalg.eig(M)
cond = (4 * evec[:, 0] * evec[:, 2]) - (evec[:, 1] ** 2)
I = np.where(cond > 0)[0]
a1 = evec[:, I[np.argmin(cond[I])]]
return np.concatenate([a1, T.dot(a1)])
def fit_improved_B2AC(points):
"""Ellipse fitting in Python with improved B2AC algorithm as described in
this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_.
This version of the fitting uses float storage during calculations and performs the
eigensolver on a float array.
:param points: The [Nx2] array of points to fit ellipse to.
:type points: :py:class:`numpy.ndarray`
:return: The conic section array defining the fitted ellipse.
:rtype: :py:class:`numpy.ndarray`
"""
points = np.array(points, 'float')
S = _calculate_scatter_matrix_py(points[:, 0], points[:, 1])
S3 = S[3:, 3:]
S3 = np.array([S3[0, 0], S3[0, 1], S3[0, 2], S3[1, 1], S3[1, 2], S3[2, 2]])
S3_inv = inverse_symmetric_3by3_double(S3).reshape((3, 3))
S2 = S[:3, 3:]
T = -np.dot(S3_inv, S2.T)
M = S[:3, :3] + np.dot(S2, T)
inv_mat = np.array([[0, 0, 0.5], [0, -1, 0], [0.5, 0, 0]], 'float')
M = inv_mat.dot(M)
e_vals, e_vect = np.linalg.eig(M)
try:
elliptical_solution_index = np.where(((4 * e_vect[0, :] * e_vect[2, :]) - ((e_vect[1, :] ** 2))) > 0)[0][0]
except:
# No positive eigenvalues. Fit was not ellipse.
raise ArithmeticError("No elliptical solution found.")
a = e_vect[:, elliptical_solution_index]
if a[0] < 0:
a = -a
return np.concatenate((a, np.dot(T, a)))
def fit_improved_B2AC_int(points):
"""Ellipse fitting in Python with improved B2AC algorithm as described in
this `paper <http://autotrace.sourceforge.net/WSCG98.pdf>`_.
This version of the fitting uses int64 storage during calculations and performs the
eigensolver on an integer array.
:param points: The [Nx2] array of points to fit ellipse to.
:type points: :py:class:`numpy.ndarray`
:return: The conic section array defining the fitted ellipse.
:rtype: :py:class:`numpy.ndarray`
"""
S = _calculate_scatter_matrix_c(points[:, 0], points[:, 1])
S1 = np.array([S[0, 0], S[0, 1], S[0, 2], S[1, 1], S[1, 2], S[2, 2]])
S3 = np.array([S[3, 3], S[3, 4], S[3, 5], S[4, 4], S[4, 5], S[5, 5]])
adj_S3, det_S3 = inverse_symmetric_3by3_int(S3)
S2 = S[:3, 3:]
T_no_det = - np.dot(np.array(adj_S3.reshape((3, 3)), 'int64'), np.array(S2.T, 'int64'))
M_term2 = np.dot(np.array(S2, 'int64'), T_no_det) // det_S3
M = add_symmetric_matrix(M_term2, S1)
M[[0, 2], :] /= 2
M[1, :] = -M[1, :]
e_vals, e_vect = np.linalg.eig(M)
try:
elliptical_solution_index = np.where(((4 * e_vect[0, :] * e_vect[2, :]) - ((e_vect[1, :] ** 2))) > 0)[0][0]
except:
# No positive eigenvalues. Fit was not ellipse.
raise ArithmeticError("No elliptical solution found.")
a = e_vect[:, elliptical_solution_index]
return np.concatenate((a, np.dot(T_no_det, a) / det_S3))
def _calculate_scatter_matrix_py(x, y):
"""Calculates the complete scatter matrix for the input coordinates.
:param x: The x coordinates.
:type x: :py:class:`numpy.ndarray`
:param y: The y coordinates.
:type y: :py:class:`numpy.ndarray`
:return: The complete scatter matrix.
:rtype: :py:class:`numpy.ndarray`
"""
D = np.ones((len(x), 6), dtype=x.dtype)
D[:, 0] = x * x
D[:, 1] = x * y
D[:, 2] = y * y
D[:, 3] = x
D[:, 4] = y
return D.T.dot(D)
def _calculate_scatter_matrix_c(x, y):
"""Calculates the upper triangular scatter matrix for the input coordinates.
:param x: The x coordinates.
:type x: :py:class:`numpy.ndarray`
:param y: The y coordinates.
:type y: :py:class:`numpy.ndarray`
:return: The upper triangular scatter matrix.
:rtype: :py:class:`numpy.ndarray`
"""
S = np.zeros((6, 6), 'int32')
for i in xrange(len(x)):
tmp_x2 = x[i] ** 2
tmp_x3 = tmp_x2 * x[i]
tmp_y2 = y[i] ** 2
tmp_y3 = tmp_y2 * y[i]
S[0, 0] += tmp_x2 * tmp_x2
S[0, 1] += tmp_x3 * y[i]
S[0, 2] += tmp_x2 * tmp_y2
S[0, 3] += tmp_x3
S[0, 4] += tmp_x2 * y[i]
S[0, 5] += tmp_x2
S[1, 2] += tmp_y3 * x[i]
S[1, 4] += tmp_y2 * x[i]
S[1, 5] += x[i] * y[i]
S[2, 2] += tmp_y2 * tmp_y2
S[2, 4] += tmp_y3
S[2, 5] += tmp_y2
S[3, 5] += x[i]
S[4, 5] += y[i]
S[5, 5] = len(x)
# Doubles
S[1, 1] = S[0, 2]
S[1, 3] = S[0, 4]
S[2, 3] = S[1, 4]
S[3, 3] = S[0, 5]
S[3, 4] = S[1, 5]
S[4, 4] = S[2, 5]
return S
|
hbldh/b2ac
|
b2ac/fit/reference.py
|
Python
|
mit
| 7,871
|
#!/usr/bin/env python
#
# eppy documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
import eppy
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
"sphinx.ext.napoleon",
"nbsphinx",
]
# extensions = ['nbsphinx']
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "eppy"
copyright = "2020, Santosh Philip"
author = "Santosh Philip"
# 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 = eppy.__version__
# The full version, including alpha/beta/rc tags.
release = eppy.__version__
# 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 = None
# 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 name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "eppydoc"
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, "eppy.tex", "eppy Documentation", "Santosh Philip", "manual"),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "eppy", "eppy Documentation", [author], 1)]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"eppy",
"eppy Documentation",
author,
"eppy",
"One line description of project.",
"Miscellaneous",
),
]
|
santoshphilip/eppy
|
docs/conf.py
|
Python
|
mit
| 4,834
|
#!/usr/bin/env python
"""
This script sends confirmation messages to recently registered users.
It should be run periodically so that users receive a registration
confirmation link soon after they have registered.
rbp@isnomore.net
"""
import smtplib
from email.message import Message
from . db import Connection
from . config import options
def create_message(email, key):
msg = Message()
msg['From'] = '{0} <{1}>'.format(options.reg_confirmation_from,
options.reg_confirmation_from_addr)
msg['To'] = email
msg['Subject'] = options.reg_confirmation_subject
body = open(options.reg_confirmation_template).read()
msg.set_payload(body.format(registration_key=key))
return msg
def mail_confirmation(email, msg):
server = smtplib.SMTP(options.smtp_server)
server.sendmail(options.reg_confirmation_from_addr,
email,
msg)
server.quit()
def send_pending_confirmations():
db_conn = Connection(options.db_params, driver=options.db_driver)
db_conn.connect()
results = {'failed': []}
pending = db_conn.get_pending_users_unmailed()
for email, key in pending:
msg = create_message(email, key)
try:
mail_confirmation(email, msg.as_string())
except Exception, e:
results['failed'].append((email, e.args))
else:
db_conn.set_pending_user_as_mailed(email)
return results
if __name__ == '__main__':
results = send_pending_confirmations()
if results:
print "Sending failed for:"
print "\n".join(i[0] for i in results["failed"])
|
rbp/auth
|
mailer.py
|
Python
|
mit
| 1,655
|
# -*- coding: utf-8 -*-
# Release information about mse
version = '1.0'
# description = "Your plan to rule the world"
# long_description = "More description about your plan"
# author = "Your Name Here"
# email = "YourEmail@YourDomain"
# copyright = "Copyright 2011 - the year of the Rabbit"
# Of it's open source, you might want to specify these:
# url = 'http://yourcool.site/'
# download_url = 'http://yourcool.site/download'
# license = 'MIT'
|
jinmingda/MicroorganismSearchEngine
|
mse/release.py
|
Python
|
mit
| 449
|
a = "python"
print(a*2)
try:
print(a[-10])
except IndexError as e:
print("인덱스 범위를 초과 했습니다.")
print(e)
print(a[0:4])
print(a[1:-2])
# -10은 hi뒤로 10칸
print("%-10sjane." % "hi")
b = "Python is best choice."
print(b.find("b"))
print(b.find("B"))
try:
print(b.index("B"))
except ValueError as e:
print(e)
c = "hi"
print(c.upper())
a = " hi"
print("kk",a.lstrip())
a = " hi "
print(a.strip())
|
JaeGyu/PythonEx_1
|
20170106.py
|
Python
|
mit
| 455
|
from unittest import TestCase
# from unittest import mock
from mwclient import Site
from bookhelper import ExistingBook
from . import PageMock, SiteMock, TESTBOOK1_TXT
#Site.login=mock.MagicMock(return_value=True)
class TestInit(TestCase):
def setUp(self):
self.site = SiteMock()
def test_book(self):
book = ExistingBook(self.site, "Testbook1", "live")
self.assertEqual(book.errors, [])
self.assertEqual(book.book_page.friendly_title, "Testbook1")
self.assertEqual(book.book_page.text.strip(), TESTBOOK1_TXT)
self.assertEqual(book.toc[0].target,'Testbook1/Page1')
self.assertEqual(book.toc[1].target,'Testbook1/Page2')
self.assertEqual(book.toc[1].text,'Page2')
|
theithec/bookhelper
|
bookhelper/tests/test_init.py
|
Python
|
mit
| 741
|
"""All forms for the extension."""
from django.forms import ModelForm
from .models import WebResource
class WebResourceForm(ModelForm):
"""Form for a single web resource."""
class Meta:
"""Form meta."""
model = WebResource
fields = ('name', 'description', 'url', 'colour', 'symbol')
|
ExCiteS/geokey-webresources
|
geokey_webresources/forms.py
|
Python
|
mit
| 321
|
import logging
from django.conf import settings
from mock_api.http_utils import make_request
logger = logging.getLogger(__name__)
def run_api_endpoint_callbacks(api_endpoint):
responses = []
for api_callback in api_endpoint.callbacks.all():
logger.debug("Make callback: %s", api_callback)
response = make_request(method=api_callback.method, url=api_callback.url, params=api_callback.get_params(),
headers=api_callback.get_headers(), timeout=settings.DEFAULT_CALLBACK_REQUEST_TIMEOUT)
if response:
logger.debug("Callback response status code: %s", response.status_code)
responses.append(response)
return responses
|
marcin-bakowski-dev/rest-api-mock-server
|
mock_rest_app/mock_api/callbacks.py
|
Python
|
mit
| 710
|
"""
Classes::
VASPData -- A collection of functions that wrap bash code to extract
data from VASP output into managable .dat (.txt) files.
"""
import numpy as np
from subprocess import call, check_output
from ast import literal_eval
class VASPData(object):
"""
A collection of functions that wrap bash code to extract
data from VASP output into managable .dat (.txt) files.
Variables::
name -- A string containing the path to the
VASP data.
Funtions::
extract_symops_trans -- Get symmetry operations and translations
from OUTCAR -> symops_trans.dat.
extract_kpts_eigenvals -- Get k-points, weights, and eigenvalues
from EIGENVAL -> kpts_eigenvals.dat.
extract_kmax -- Get kmax from KPOINTS -> kmax.dat (details about
what kmax is are given in readdata.py).
"""
def __init__(self, name_of_data_directory, kpts_eigenvals=True,
symops_trans=True, kmax=True):
"""
Arguments::
name_of_data_directory -- See Variables::name.
Keyword Arguments::
kpts_eigenvals, symops_trans, kmax -- All are booleans that
specify if that bit of data should be extracted from the
VASP output files. One may use False if the corresponding
.dat file already exists or is handmade. Default is True for
all three.
"""
self.name = name_of_data_directory
if kpts_eigenvals:
self.extract_kpts_eigenvals()
if symops_trans:
self.extract_symops_trans()
if kmax:
self.extract_kmax()
def extract_symops_trans(self):
"""
Use some bash code to look inside OUTCAR, grab the
symmetry operators and translations, and then write them to a
file called symops_trans.dat. File is written to the same folder
the OUTCAR is in.
"""
name = self.name
call("grep -A 4 -E 'isymop' " + name + "/OUTCAR | cut -c 11-50 > " +
name + "/symops_trans.dat; echo '' >> " + name +
"/symops_trans.dat", shell=True)
def extract_kpts_eigenvals(self):
""""
Use some bash code to look inside EIGENVAL and grab the
k-points, weights, and eigenvalues associated with each band at
each k-point. Write them to a file called kpts_eigenvals.dat.
File is written to the same folder the EIGENVAL is in.
"""
name = self.name
length = check_output('less ' + name + '/EIGENVAL | wc -l', shell=True)
num = str([int(s) for s in length.split() if s.isdigit()][0] - 7)
call('tail -n' + num + ' ' + name +
'/EIGENVAL | cut -c 1-60 > ' + name + '/kpts_eigenvals.dat',
shell=True)
def extract_kmax(self):
"""
Look inside KPOINTS and grab the number of kpoints used in
one direction. If the grid is not cubic i.e. 12 12 5 it will
take the smallest. Also assumes the KPOINTS has this format:
nxmxp! comment line
0
Monkhorst
12 12 12
0 0 0
at least as far as what line the 12 12 12 is on. To be concrete
the only requirement is that the grid is specified on
the fourth line. If one wishes to use a different format for the
KPOINTS file they can set the kmax bool to False and generate
their own kmax.dat in the same directory as the VASP data to be
used by readdata.py. GRID SIZE ON FOURTH LINE.
"""
name = self.name
with open(name+'/KPOINTS', 'r') as inf:
line = [literal_eval(x) for x in
inf.readlines()[3].strip().split()]
k = min(line)
kmax = np.ceil(k/(2*np.sqrt(3)))
with open(name+'/kmax.dat', 'w') as outf:
outf.write(str(kmax))
|
mmb90/dftintegrate
|
dftintegrate/fourier/vaspdata.py
|
Python
|
mit
| 3,878
|
import unittest
from GUI.PopUps.FileHandlerPopUp import FileHandlerPopUp
from Constants.FileHandlingMode import *
class TestFileHandlingPopUp(unittest.TestCase):
def setUp(self):
self.title = "test"
self.callbackbuttontext = "button"
self.path = "test_path"
self.filters = ["*.jpg", "*.test"]
self.imported_files = []
self.selected_presentations = []
self.presentation_names = ["test1", "test2"]
self.open_project_layout = FileHandlerPopUp(title=self.title,
default_path=self.path,
callback=self.open_callback,
callback_button_text=self.callbackbuttontext,
file_handling_mode=OpenProject,
test_mode=True)
self.import_multiple_layout = FileHandlerPopUp(title=self.title,
default_path=self.path,
callback=self.import_multiple_callback,
callback_button_text=self.callbackbuttontext,
file_handling_mode=ImportMultipleFiles,
imported_files=self.imported_files,
selected_presentations=self.selected_presentations,
presentation_names=self.presentation_names,
filters=self.filters,
test_mode=True)
self.save_project_layout = FileHandlerPopUp(title=self.title,
default_path=self.path,
callback=self.save_callback,
callback_button_text=self.callbackbuttontext,
file_handling_mode=SaveProject,
test_mode=True)
def open_callback(self, path, list, filename):
pass
def save_callback(self, path, list, filename):
pass
def import_multiple_callback(self, path, list, filename):
pass
def test_callback_button_on_open_project_popup_1(self):
self.assertTrue(self.open_project_layout.ids.callback_button.disabled)
def test_callback_button_on_open_project_popup_2(self):
self.open_project_layout.ids.filechooser.selection.append("test")
self.open_project_layout.check_selections(None, None)
self.assertFalse(self.open_project_layout.ids.callback_button.disabled)
def test_callback_button_on_import_multiple_popup_1(self):
self.assertTrue(self.import_multiple_layout.ids.callback_button.disabled)
def test_callback_button_on_import_multiple_popup_2(self):
self.import_multiple_layout.ids.filechooser.selection.append("test")
self.import_multiple_layout.check_selections(None, None)
self.assertTrue(self.import_multiple_layout.ids.callback_button.disabled)
def test_callback_button_on_import_multiple_popup_3(self):
self.import_multiple_layout.selected_presentations.append("test")
self.import_multiple_layout.check_selections(None, None)
self.assertTrue(self.import_multiple_layout.ids.callback_button.disabled)
def test_callback_button_on_import_multiple_popup_4(self):
self.import_multiple_layout.ids.filechooser.selection.append("test")
self.import_multiple_layout.selected_presentations.append("test")
self.import_multiple_layout.check_selections(None, None)
self.assertFalse(self.import_multiple_layout.ids.callback_button.disabled)
def test_filename_input_with_valid_filename(self):
self.assertTrue(self.save_project_layout.ids.callback_button.disabled)
self.save_project_layout.check_filename(None, ".ekieki")
self.assertFalse(self.save_project_layout.ids.callback_button.disabled)
def test_filename_with_invalid_filename(self):
self.assertTrue(self.save_project_layout.ids.callback_button.disabled)
self.save_project_layout.check_filename(None, "\\ekieki")
self.assertTrue(self.save_project_layout.ids.callback_button.disabled)
def test_filename_with_empty_filename(self):
self.assertTrue(self.save_project_layout.ids.callback_button.disabled)
self.save_project_layout.check_filename(None, "")
self.assertTrue(self.save_project_layout.ids.callback_button.disabled)
|
RemuTeam/Remu
|
project/tests/GUI/PopUps/test_file_handling_popup.py
|
Python
|
mit
| 4,820
|
# Generated by Django 2.2.1 on 2019-06-10 19:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registration', '0003_limbomember_mother_tongue'),
]
operations = [
migrations.RenameModel(
old_name='LimboMember',
new_name='Applicant',
),
]
|
Teknologforeningen/teknologr.io
|
teknologr/registration/migrations/0004_auto_20190610_2250.py
|
Python
|
mit
| 350
|
import os
import pytest
@pytest.fixture(scope='session')
def testdata():
"""
Simple fixture to return reference data
:return:
"""
class TestData():
def __init__(self):
self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
def fn(self, fn):
return os.path.join(self.datadir, fn)
def textdata(self, fn):
with open(self.fn(fn), encoding='utf8') as f:
return f.read()
return TestData()
|
miroag/mfs
|
tests/conftest.py
|
Python
|
mit
| 516
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_protein_motif_encoder
----------------------------------
Tests for `protein_motif_encoder` module.
"""
import pandas as pd
import pytest
from click.testing import CliRunner
import cli
def test_command_line_interface():
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'protein_motif_encoder.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
assert '--help Show this message and exit.' in help_result.output
|
tbrittoborges/protein_motif_encoder
|
tests/test_protein_motif_encoder.py
|
Python
|
mit
| 597
|
from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging by default."""
return ""
def set_base_prompt(self, pri_prompt_terminator='$',
alt_prompt_terminator='#', delay_factor=1):
"""Determine base prompt."""
return super(CiscoSSHConnection, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor)
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""Can't exit from root (if root)"""
if self.username == "root":
exit_config_mode = False
return super(CiscoSSHConnection, self).send_config_set(config_commands=config_commands,
exit_config_mode=exit_config_mode,
**kwargs)
def check_config_mode(self, check_string='#'):
"""Verify root"""
return self.check_enable_mode(check_string=check_string)
def config_mode(self, config_command='sudo su'):
"""Attempt to become root."""
return self.enable(cmd=config_command)
def exit_config_mode(self, exit_config='exit'):
return self.exit_enable_mode(exit_command=exit_config)
def check_enable_mode(self, check_string='#'):
"""Verify root"""
return super(CiscoSSHConnection, self).check_enable_mode(check_string=check_string)
def exit_enable_mode(self, exit_command='exit'):
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
time.sleep(.3 * delay_factor)
self.set_base_prompt()
if self.check_enable_mode():
raise ValueError("Failed to exit enable mode.")
return output
def enable(self, cmd='sudo su', pattern='ssword', re_flags=re.IGNORECASE):
"""Attempt to become root."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if not self.check_enable_mode():
self.write_channel(self.normalize_cmd(cmd))
time.sleep(.3 * delay_factor)
try:
output += self.read_channel()
if re.search(pattern, output, flags=re_flags):
self.write_channel(self.normalize_cmd(self.secret))
self.set_base_prompt()
except socket.timeout:
raise NetMikoTimeoutException("Timed-out reading channel, data not available.")
if not self.check_enable_mode():
msg = "Failed to enter enable mode. Please ensure you pass " \
"the 'secret' argument to ConnectHandler."
raise ValueError(msg)
return output
|
isidroamv/netmiko
|
netmiko/linux/linux_ssh.py
|
Python
|
mit
| 3,207
|
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="scatter.unselected.textfont", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
plotly/python-api
|
packages/python/plotly/plotly/validators/scatter/unselected/textfont/_color.py
|
Python
|
mit
| 470
|
from flask import (Blueprint, current_app as app,
g, request, make_response,
jsonify, session)
from ..models import ModelError, Session
from ..models.post import Post, Draft, PostOperator
from .helpers import (require_int, JumpDirectly)
api_bp = Blueprint('api', __name__)
post_op = PostOperator(Session())
def get_plain_dict(post, meta):
post_dict = post.as_dict(meta)
if 'created_at' in post_dict:
post_dict['created_at'] = post_dict['created_at'] and \
unicode(post_dict['created_at'])
if 'updated_at' in post_dict:
post_dict['updated_at'] = post_dict['updated_at'] and \
unicode(post_dict['updated_at'])
return post_dict
def jsonify_error(message, status):
return make_response(
jsonify({'stat': 'fail',
'message': message}),
status)
def jsonify_posts(posts, meta=False, **kwargs):
response = kwargs
response.update({'posts': [get_plain_dict(post, meta) for post in posts],
'total_posts': len(posts)})
return jsonify({'stat': 'ok',
'response': response})
def get_status_code(status_string):
""" Parse status string like public+private into a list of status code. """
statuses = status_string.lower().split('+')
status_code = []
for status in set(statuses):
if status == 'public':
status_code.append(Post.STATUS_PUBLIC)
elif status == 'private':
status_code.append(Post.STATUS_PRIVATE)
if not g.is_admin:
raise JumpDirectly(jsonify_error('admin required', 403))
elif status == 'trash':
status_code.append(Post.STATUS_TRASH)
if not g.is_admin:
raise JumpDirectly(jsonify_error('admin required', 403))
else:
raise JumpDirectly(jsonify_error('invalid status', 400))
if len(status_code) == 0:
raise JumpDirectly(jsonify_error('status not found', 400))
return status_code
@api_bp.route('/drafts/', methods=['DELETE'])
def delete_drafts():
if not g.is_admin:
return jsonify_error('admin required', 403)
ids = [require_int(id, JumpDirectly(jsonify_error('invalid draft id', 400)))
for id in request.args.get('bulk', '').split(',') if id.strip()]
if len(ids) > 0:
deleted_rows = post_op.session.query(Draft).\
filter(Draft.id.in_(ids)).\
delete(synchronize_session='fetch')
post_op.session.commit()
else:
deleted_rows = 0
return jsonify({'stat': 'ok', 'response': {'total_drafts': deleted_rows}})
@api_bp.route('/posts/', methods=['DELETE'])
def delete_posts():
"""
Delete posts from server.
* admin required
* optional arguments: bulk, status
bulk is a list of post IDs separated by comma.
"""
if not g.is_admin:
return jsonify_error('admin required', 403)
posts = []
# get posts from post IDs
ids = [require_int(id, JumpDirectly(jsonify_error('invalid post id', 400)))
for id in request.args.get('bulk', '').split(',') if id.strip()]
if len(ids) > 0:
posts = post_op.session.query(Post).filter(Post.id.in_(ids)).all()
# get all posts in specified status
status = request.args.get('status')
if status:
status_code = get_status_code(status)
posts += post_op.session.query(Post).\
filter(Post.status.in_(status_code)).all()
# delete all of them
if len(posts) > 0:
post_op.delete_posts(posts)
return jsonify({'stat': 'ok', 'response': {'total_posts': len(posts)}})
@api_bp.route('/posts/', methods=['POST'])
def create_post():
"""
Create a post. Return the post.
* admin required
* required post data: title, slug
* optional post data: text, tags, private
"""
if not g.is_admin:
return jsonify_error('admin required', 403)
title = request.form.get('title')
if not title:
return jsonify_error('title required', 400)
slug = request.form.get('slug')
if not slug:
return jsonify_error('slug required', 400)
post = post_op.get_post_by_permalink(slug)
if post is not None:
return jsonify_error('slug is not unique', 400)
private = bool(request.form.get('private', False))
text = request.form.get('text')
tags = request.form.get('tags')
author_id = session['uid']
if tags:
tags = tags.split()
try:
post = Post(title=title, text=text,
slug=slug, author_id=author_id)
if private:
post.status = Post.STATUS_PRIVATE
post_op.create_post(post)
if tags:
post.set_tags(tags)
except ModelError as err:
return jsonify_error(err.message, 400)
return jsonify_posts([post])
@api_bp.route('/posts/')
def get_posts():
"""
Get posts.
* admin required
* arguments: offset, limit, status, meta, sort, asc, tags, id
"""
offset = require_int(request.args.get('offset', 0),
JumpDirectly(jsonify_error('invalid offset', 400)))
limit = require_int(
request.args.get('limit', app.config['POST_API_PERPAGE']),
JumpDirectly(jsonify_error('invalid limit', 400)))
status = request.args.get('status', 'public+private').lower()
# admin may be required in this function
status_code = get_status_code(status)
meta = 'meta' in request.args
sort = request.args.get('sort', 'created_at')
# if asc argument is found, do asc sort
asc = 'asc' in request.args
tags = request.args.get('tags')
id = request.args.get('id')
if id is None:
# get multi posts
try:
posts, more = post_op.query_posts(
status=status_code, offset=offset, limit=limit,
tags=tags and tags.split('+'),
date=None, sort=sort, asc=asc)
except ModelError as err:
return jsonify_error(err.message, 400)
else:
# get single post when post id is specified
more = False
id = require_int(id, JumpDirectly(jsonify_error('invalid id', 400)))
post = post_op.get_post(id)
if post is None:
return jsonify_error('post not found', 404)
else:
if not g.is_admin and (post.status in (Post.STATUS_PRIVATE,
Post.STATUS_TRASH)):
return jsonify_error('admin required', 403)
posts = [post]
return jsonify_posts(posts, meta, more=more)
def set_status(status):
"""
Set post status (publish, hide, or trash post)
* admin required
* required arguments: id, or id list
"""
if not g.is_admin:
return jsonify_error('admin required', 403)
if status not in [Post.STATUS_TRASH, Post.STATUS_PUBLIC, Post.STATUS_PRIVATE]:
return jsonify_error('invalid status', 400)
id_param = request.form.get('id')
if id_param is None:
return jsonify_error('invalid id parameter', 400)
id_list = [require_int(id, JumpDirectly(jsonify_error('invalid id', 400)))
for id in id_param.split(',')]
posts = post_op.session.query(Post).filter(Post.id.in_(id_list)).all()
for post in posts:
post.status = status
post_op.session.commit()
return jsonify_posts(posts, meta=True)
@api_bp.route('/posts/trash', methods=['POST'])
def trash_posts():
return set_status(Post.STATUS_TRASH)
@api_bp.route('/posts/publish', methods=['POST'])
def publish_posts():
return set_status(Post.STATUS_PUBLIC)
@api_bp.route('/posts/hide', methods=['POST'])
def hide_posts():
return set_status(Post.STATUS_PRIVATE)
|
ptpt/taoblog
|
taoblog/views/api.py
|
Python
|
mit
| 7,738
|
"""
Represents protected content
"""
from django.conf.urls import url
from django.http import HttpResponse
def testview(request):
return HttpResponse()
urlpatterns = [url(r"^$", testview, name="test_url_content")]
|
kavdev/dj-stripe
|
tests/apps/testapp_content/urls.py
|
Python
|
mit
| 220
|
from flask import current_app, redirect, url_for, request, session, flash, send_file
from flask.ext import restful
from flask.ext.login import login_required, current_user, login_user, logout_user
import twitter
from request_parsers import *
from datetime import datetime
from models import *
from rauth.service import OAuth1Service
from rauth.utils import parse_utf8_qsl
from twitter_helpers import TwitterUser
import controllers
import traceback
class TwitterAuth(restful.Resource):
def get(self):
twitter_auth_loader = OAuth1Service(
name='twitter',
consumer_key=current_app.config['CONSUMER_KEY'],
consumer_secret=current_app.config['CONSUMER_SECRET'],
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authorize',
base_url='https://api.twitter.com/1.1/'
)
oauth_callback = url_for('twittercallback', _external=True)
params = {'oauth_callback': oauth_callback}
auth_url = twitter_auth_loader.get_raw_request_token(params=params)
data = parse_utf8_qsl(auth_url.content)
session['twitter_oauth'] = (data['oauth_token'],
data['oauth_token_secret'])
return redirect(twitter_auth_loader.get_authorize_url(data['oauth_token'], **params))
class Login(restful.Resource):
def get(self):
return send_file('views/index.html')
#return current_app.send_static_file('views/login.html')
return {'status':'Welcome'}
class TwitterCallback(restful.Resource):
def get(self):
try:
print session
request_token, request_token_secret = session.pop('twitter_oauth')
twitter_auth_loader = OAuth1Service(
name='twitter',
consumer_key=current_app.config['CONSUMER_KEY'],
consumer_secret=current_app.config['CONSUMER_SECRET'],
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authorize',
base_url='https://api.twitter.com/1.1/'
)
if not 'oauth_token' in request.args:
print 'You did not authorize the request'
return redirect(url_for('index'))
try:
creds = {'request_token': request_token,
'request_token_secret': request_token_secret}
params = {'oauth_verifier': request.args['oauth_verifier']}
sess = twitter_auth_loader.get_auth_session(params=params, **creds)
print sess.access_token
except Exception, e:
flash('There was a problem logging into Twitter: ' + str(e))
return redirect(url_for('index'))
api = twitter.Api(
current_app.config['CONSUMER_KEY'],
current_app.config['CONSUMER_SECRET'],
sess.access_token,
sess.access_token_secret
)
u = api.VerifyCredentials()
user = User.objects(twitter_id = u.id).first()
if not user:
user = User(twitter_id = u.id, screen_name = u.screen_name, registered_on = datetime.now(), access_token = sess.access_token, access_token_secret = sess.access_token_secret)
user.save()
else:
user.update(set__access_token = sess.access_token, set__access_token_secret = sess.access_token_secret)
login_user(user)
# return controllers.get_logged_in_users_list(user)
return redirect('http://localhost:8000')
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'Internal Server Error.')
class MyLists(restful.Resource):
@login_required
def get(self):
#args = list_parser.parse_args()
#TODO also return subscribed lists
user = current_user
try:
return controllers.get_logged_in_users_list(user)
pass
except twitter.TwitterError as e:
if e.message[0]['code'] == 88:
restful.abort(404, message = 'Limit for your access token has reached. Be patient and see some of the popular timelines')
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'internal server error.')
class CreateList(restful.Resource):
@login_required
def get(self):
args = create_list_parser.parse_args()
user = current_user
try:
return controllers.create_list(user, args['screen_name'])
pass
except twitter.TwitterError as e:
if e.message[0]['code'] == 34:
restful.abort(404, message = 'Sorry user not found on twitter.')
elif e.message[0]['code'] == 88:
restful.abort(404, message = 'Limit for your access token has reached. You can create more timenlines later. Try some of the popular timelines for now.')
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'internal server error.')
class SubscribeList(restful.Resource):
@login_required
def get(self):
args = subscribe_list_parser.parse_args()
user = current_user
try:
return controllers.subscribe_list(user, args['list_id'], args['owner_id'])
except twitter.TwitterError as e:
if e.message[0]['code'] == 88:
restful.abort(404, message = 'Limit for your access token has reached. You may subscribe to interesting timelines later. Just enjoy popular timelines for now.')
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'internal server error.')
class DiscoverList(restful.Resource):
@login_required
def get(self):
args = discover_list_parser.parse_args()
try:
list_objs = list(TimelineList._get_collection().find({'exists' : True}).skip(args['skip']).limit(args['limit']))
map(lambda x:x.pop('_id'),list_objs)
return list_objs
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'internal server error.')
class ListTimeline(restful.Resource):
@login_required
def get(self):
args = list_timeline_parser.parse_args()
user = current_user
try:
return controllers.list_timeline(user, args['list_id'], args['owner_id'], args['since_id'], args['count'])
except twitter.TwitterError as e:
if e.message[0]['code'] == 34:
controllers.update_list_status(args['list_id'], exists = False)
restful.abort(404, message = 'Sorry page not found')
except Exception as e:
import traceback
print traceback.format_exc(e)
restful.abort(500, message = 'internal server error.')
|
airwoot/timeline-hack-core
|
app/resources.py
|
Python
|
mit
| 7,302
|
#!/usr/bin/python
""" README
This script is deprecated. Please use https://github.com/device42/servicenow_device42_mapping
This script reads CIs from Servicenow and uploads them to Device42.
It has 2 modes:
1. Full migration - when the TIMEFRAME is set to 0
2. Synchronization - when the TIMEFRAME is set to anything else but 0
GOTCHAS
* In order for hardwares to be migrated, hardware must have unique name.
* When there are multiple devices with the same name, device name is constructed as: "device_name" + "_" + "servicenow_sys_id"
i.e. " MacBook Air 13" " will become " MacBook Air 13"_01a9280d3790200044e0bfc8bcbe5d79 "
*
"""
import sys
from srvnow2d42 import ServiceNow
__version__ = "2.0.2"
__status__ = "Production"
# ===== Device42 ===== #
D42_USER = 'admin'
D42_PWD = 'adm!nd42'
D42_URL = 'https://192.168.3.30'
# ===== ServiceNow ===== #
USERNAME = 'admin'
PASSWORD = 'admin123'
BASE_URL = 'https://dev13852.service-now.com/api/now/table/'
LIMIT = 1000000 # number of CIs to retrieve from ServiceNow
HEADERS = {"Content-Type":"application/json","Accept":"application/json"}
TABLES = ['cmdb_ci_server' , 'cmdb_ci_computer', 'cmdb_ci_app_server', 'cmdb_ci_database', 'cmdb_ci_email_server',
'cmdb_ci_ftp_server', 'cmdb_ci_directory_server', 'cmdb_ci_ip_server']
# ===== Other ===== #
DEBUG = True # print to STDOUT
DRY_RUN = False # Upload to Device42 or not
ZONE_AS_ROOM = True # for the explanation take a look at get_zones() docstring
TIMEFRAME = 0 # Value represents hours. If set to 0, script does full migration, if set to any other value,
# script syncs changes back from till now(). now() refers to current localtime.
if __name__ == '__main__':
snow = ServiceNow(D42_URL, D42_USER, D42_PWD, USERNAME, PASSWORD, BASE_URL, LIMIT,
HEADERS, DEBUG, DRY_RUN, ZONE_AS_ROOM, TIMEFRAME)
snow.create_db()
snow.get_relationships()
snow.get_manufacturers()
snow.get_hardware()
snow.get_locations()
snow.get_buildings()
snow.get_rooms()
if ZONE_AS_ROOM:
snow.get_zones()
snow.get_racks()
for table in TABLES:
snow.get_computers(table)
snow.get_adapters()
snow.get_ips()
snow.upload_adapters()
sys.exit()
|
device42/servicenow_to_device42_sync
|
starter.py
|
Python
|
mit
| 2,360
|
# -*- coding: utf-8 -*-
import os
import ntpath
import glob
from pyhammer.tasks.taskbase import TaskBase
from pyhammer.utils import execProg
class MakeNugetPackageTask(TaskBase):
"""Make Nuget Package Task"""
def __init__( self, csProjectPath, solutionDir, tempDir, publishDir, visualStudioVersion = "12.0" ):
super(MakeNugetPackageTask, self).__init__()
self.csProjectPath = csProjectPath
self.solutionDir = solutionDir
self.tempDir = tempDir
self.publishDir = publishDir
self.visualStudioVersion = visualStudioVersion
def do( self ):
self.reporter.message( "MAKING NUGET PACKAGE FROM: %s" % ntpath.basename(self.csProjectPath) )
result = execProg("msbuild.exe \"%s\" /t:Rebuild /p:Configuration=Release;VisualStudioVersion=%s" % ( self.csProjectPath, self.visualStudioVersion ), self.reporter, self.solutionDir)
if(not result == 0):
return False
result = execProg("nuget.exe pack \"%s\" -IncludeReferencedProjects -prop Configuration=Release -OutputDirectory \"%s\"" % (self.csProjectPath, self.tempDir), self.reporter)
if(not result == 0):
return False
if(self.publishDir is not None):
os.chdir(self.tempDir)
files = glob.glob("*.nupkg")
result = execProg("nuget.exe push \"%s\" -Source \"%s\"" % (files[0], self.publishDir), self.reporter)
os.remove(files[0])
if(not result == 0):
return False
return True
|
webbers/pyhammer
|
pyhammer/tasks/helpers/makenugetpackagetask.py
|
Python
|
mit
| 1,540
|
"""add-hikes
Revision ID: f7888bd46c75
Revises: 820bb005f2c5
Create Date: 2017-02-16 07:36:06.108806
"""
# revision identifiers, used by Alembic.
revision = 'f7888bd46c75'
down_revision = 'fc92ba2ffd7f'
from alembic import op
import sqlalchemy as sa
import geoalchemy2
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('hike_destination',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('altitude', sa.Integer(), nullable=True),
sa.Column('high_point_coord', geoalchemy2.types.Geometry(geometry_type='POINT'), nullable=False),
sa.Column('is_summit', sa.Boolean(), server_default='t', nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.text(u'now()'), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('hike',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('destination_id', sa.Integer(), nullable=False),
sa.Column('datetime', sa.DateTime(), server_default=sa.text(u'now()'), nullable=False),
sa.Column('method', sa.String(length=30), nullable=False),
sa.Column('notes', sa.Text(), server_default='', nullable=False),
sa.CheckConstraint(u"method in ('ski', 'foot', 'crampons', 'climb', 'via ferrata')"),
sa.ForeignKeyConstraint(['destination_id'], [u'hike_destination.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('hike')
op.drop_table('hike_destination')
### end Alembic commands ###
|
thusoy/blag
|
blag/migrations/versions/f7888bd46c75_add_hikes.py
|
Python
|
mit
| 1,664
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import unittest
class OpenCCTest(unittest.TestCase):
def setUp(self):
self.openCC = OpenCC()
def test_hk2s(self):
self.openCC.set_conversion('hk2s')
words = '香煙(英語:Cigarette),為煙草製品的一種。滑鼠是一種很常見及常用的電腦輸入設備。'
self.assertEqual(self.openCC.convert(words), '香烟(英语:Cigarette),为烟草制品的一种。滑鼠是一种很常见及常用的电脑输入设备。')
def test_s2hk(self):
self.openCC.set_conversion('s2hk')
words = '香烟(英语:Cigarette),为烟草制品的一种。鼠标是一种很常见及常用的电脑输入设备。'
self.assertEqual(self.openCC.convert(words), '香煙(英語:Cigarette),為煙草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。')
def test_s2t(self):
self.openCC.set_conversion('s2t')
words = '香烟(英语:Cigarette),为烟草制品的一种。鼠标是一种很常见及常用的电脑输入设备。'
self.assertEqual(self.openCC.convert(words), '香菸(英語:Cigarette),爲菸草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。')
def test_s2tw(self):
self.openCC.set_conversion('s2tw')
words = '香烟(英语:Cigarette),为烟草制品的一种。鼠标是一种很常见及常用的电脑输入设备。'
self.assertEqual(self.openCC.convert(words), '香菸(英語:Cigarette),為菸草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。')
def test_s2twp(self):
self.openCC.set_conversion('s2twp')
words = '香烟(英语:Cigarette),为烟草制品的一种。內存是一种很常见及常用的电脑输入设备。'
self.assertEqual(self.openCC.convert(words), '香菸(英語:Cigarette),為菸草製品的一種。記憶體是一種很常見及常用的電腦輸入裝置。')
def test_t2hk(self):
self.openCC.set_conversion('t2hk')
words = '香菸(英語:Cigarette),爲菸草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。'
self.assertEqual(self.openCC.convert(words), '香煙(英語:Cigarette),為煙草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。')
def test_t2s(self):
self.openCC.set_conversion('t2s')
words = '香菸(英語:Cigarette),爲菸草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。'
self.assertEqual(self.openCC.convert(words), '香烟(英语:Cigarette),为烟草制品的一种。滑鼠是一种很常见及常用的电脑输入装置。')
def test_t2tw(self):
self.openCC.set_conversion('t2tw')
words = '香菸(英語:Cigarette),爲菸草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。'
self.assertEqual(self.openCC.convert(words), '香菸(英語:Cigarette),為菸草製品的一種。鼠標是一種很常見及常用的電腦輸入設備。')
def test_tw2s(self):
self.openCC.set_conversion('tw2s')
words = '香菸(英語:Cigarette),為菸草製品的一種。滑鼠是一種很常見及常用的電腦輸入裝置。'
self.assertEqual(self.openCC.convert(words), '香烟(英语:Cigarette),为烟草制品的一种。滑鼠是一种很常见及常用的电脑输入装置。')
def test_tw2sp(self):
self.openCC.set_conversion('tw2sp')
words = '香菸(英語:Cigarette),為菸草製品的一種。記憶體是一種很常見及常用的電腦輸入裝置。'
self.assertEqual(self.openCC.convert(words), '香烟(英语:Cigarette),为烟草制品的一种。内存是一种很常见及常用的电脑输入设备。')
if __name__ == '__main__':
sys.path.append(os.pardir)
from opencc import OpenCC
unittest.main()
|
jokerYellow/TranslateFiles
|
test/conversion_test.py
|
Python
|
mit
| 4,082
|