web2py routing for all controllers? - python

i want something like this using web2py routing :
domain.com/App/controller/view/args?profile Id=XX
domain.com/App/profile Id/controller/view/args
i try this code :
routes_in = (
('/App-name/(?P<any>.*)/$c/$f/', '/App-name/$c/$f/\g<any>'),
)
routes_out = (
('/App-name/$c/$f/\g<any>', '/App-name/(?P<any>.*)/$c/$f/'),
)
thank you

its work now
routes_in = (
('/admin','/admin'),
('/admin/$anything','/admin/$anything'),
('/$app/appadmin','/$app/appadmin'),
('/$app/appadmin/$anything','/$app/appadmin/$anything'),
('/Appname/$profileid/','/Appname/default/index/$profileid'),
('/Appname/$profileid/$c/$f/','/Appname/$c/$f/$profileid'),
('/Appname/$profileid/$c/$f/$arg1','/Appname/$c/$f/$arg1/$profileid'),
('/Appname/$profileid/$c/$f/$arg1/$arg2','/Appname/$c/$f/$arg1/$arg2/$profileid'),
)
routes_out = (
('/admin','/admin'),
('/admin/$anything','/admin/$anything'),
('/$app/appadmin','/$app/appadmin'),
('/$app/appadmin/$anything','/$app/appadmin/$anything'),
('/Appname/default/index/$profileid','/Appname/$profileid/'),
('/Appname/$c/$f/$profileid','/Appname/$profileid/$c/$f/'),
('/Appname/$c/$f/$arg1/$profileid','/Appname/$profileid/$c/$f/$arg1'),
('/Appname/$c/$f/$arg1/$arg2/$profileid','/Appname/$profileid/$c/$f/$arg1/$arg2'),
)

Related

Code="InvalidResourceReference" - Resource not found error when I want to create Azure Application Gateway with Pulumi

I want to create an Azure Application Gateway with Pulumi.(Document)
In some parts of the code, I should add id for example in backend_pool or etc. This idis related to the application gateway that should be created.
But when I run pulumi run I received the below error:
error: Code="InvalidResourceReference" Message="Resource /subscriptions/**/resourceGroups/RG-WAF**-GX/providers/Microsoft.Network/applicationGateways/APPGW-TEST7581 referenced by resource /subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/application_gateway_waf82529b3f was not found. Please make sure that the referenced resource exists, and that both resources are in the same region." Details=[{"code":"NotFound","message":"Resource /subscriptions/***/resourceGroups/RG-WAF**-GX/providers/Microsoft.Network/applicationGateways/APPGW-TEST7581 not found."}]
my code is:
application_gateway_waf = network.ApplicationGateway("application_gateway_waf",
location="eastus",
sku=network.ApplicationGatewaySkuArgs(
capacity=2,
name="Standard_v2",
tier="Standard_v2",
),
resource_group_name='rg-waf-gx',
gateway_ip_configurations=[network.ApplicationGatewayIPConfigurationArgs(
name="appwg_ip_config",
subnet=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/virtualNetworks/test-waf-vnet7581/subnets/appgw-subnet",
),
)],
frontend_ip_configurations=[network.ApplicationGatewayFrontendIPConfigurationArgs(
name="appgw_front_ip_config",
public_ip_address=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/publicIPAddresses/pip-appgw-waf7581",
),
)],
frontend_ports=[network.ApplicationGatewayFrontendPortArgs(
name="appgw_front_port",
port=80,
)],
backend_address_pools=[network.ApplicationGatewayBackendAddressPoolArgs(
backend_addresses=[network.ApplicationGatewayBackendAddressArgs(
fqdn = "web-app-waf7581.azurewebsites.net",
)],
name="backend_portal",
)],
backend_http_settings_collection=[network.ApplicationGatewayBackendHttpSettingsArgs(
name="backend_portal_http_setting",
protocol="http",
port=80,
cookie_based_affinity="Disabled",
request_timeout=20,
pick_host_name_from_backend_address=True,
probe=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/probes/probe_portal_backend_setting4848488484"
),
)],
http_listeners=[network.ApplicationGatewayHttpListenerArgs(
name="listener_portal",
frontend_ip_configuration=network.SubResourceArgs(
id= "/subscriptions/****/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/frontendIPConfigurations/appgw_front_ip_config",
),
frontend_port=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/frontendPorts/appgw_front_port",
),
protocol="http",
ssl_certificate= None,
host_name="portal1.mohsenakhavan.com",
require_server_name_indication= False,
)],
request_routing_rules=[network.ApplicationGatewayRequestRoutingRuleArgs(
name="rule_portal",
backend_address_pool=network.SubResourceArgs(
id="/subscriptions/****/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/backendAddressPools/backend_portal",
),
http_listener=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/httpListeners/linstener",
),
backend_http_settings=network.SubResourceArgs(
id="/subscriptions/***/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/backendHttpSettingsCollection/backend_portal_http_setting",
),
priority=100,
)],
enable_http2=False,
probes=[network.ApplicationGatewayProbeArgs(
name="probe_portal_backend_setting",
id="/subscriptions/**/resourceGroups/rg-waf645-gx/providers/Microsoft.Network/applicationGateways/appgw-test7581/backendHttpSettingsCollection/backend_portal_http_setting",
interval=30,
min_servers=0,
path="/",
protocol="Http",
timeout=30,
unhealthy_threshold=20,
pick_host_name_from_backend_http_settings=True,
)],
)
My problem was solved. I missed adding application_gateway_name item to my code. Regarding this issue, the Application Gateway return wrong name in id filed.

pyOpenSSL : verify certificates chain : works with 2 but not with more

I build my own certificates chain and try to verify it.
When I have only 2 certificates (the root CA and the to-be-verified): it works fine.
When I have 3 (the root CA, an intermediate, and the to-be-verified): I get the message "invalid CA certificate".
Here is a minimalist code :
import OpenSSL
def create_cert_chain ( nb ):
chain = []
issuer_key = None
issuer_name = None
is_root = True
for i in range( nb ):
my_name = b'certificate #%d'%i # certificate #0 is the root CA
cert = OpenSSL.crypto.X509()
my_key = OpenSSL.crypto.PKey()
my_key . generate_key( OpenSSL.crypto.TYPE_RSA,2048 )
if is_root :
cert.add_extensions( [OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash",subject=cert)])
cert.add_extensions( [OpenSSL.crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always",issuer=cert)])
cert.add_extensions( [OpenSSL.crypto.X509Extension(b"basicConstraints", False, b"CA:TRUE,pathlen:5")])
cert.add_extensions( [OpenSSL.crypto.X509Extension(b"keyUsage", False, b"keyCertSign, cRLSign")])
cert.get_subject().O = my_name
cert.get_issuer().O = my_name if is_root else issuer_name
cert.gmtime_adj_notBefore( 0 )
cert.gmtime_adj_notAfter( 365*24*60*60 )
cert.set_pubkey( my_key )
cert.sign( my_key if is_root else issuer_key,'sha256' )
chain += [cert]
issuer_key = my_key
issuer_name = my_name
is_root = False
return chain
def check_chain ( nb ):
chain = create_cert_chain( nb )
store = OpenSSL.crypto.X509Store()
for cert in chain[:-1] :
print( 'store certificate%s'%cert.get_subject().O )
store.add_cert( cert )
print( 'check certificate%s'%chain[-1].get_subject().O )
ctx = OpenSSL.crypto.X509StoreContext( store,chain[-1] )
ctx.verify_certificate()
print('ok')
check_chain( 2 ) # works fine
check_chain( 3 ) # fails with "invalid CA certificate"
What do I wrong ?
I suspect a mistake about the extensions but I can't figure out what it is...
And by the way, why does it works with only 2 certificates ?
I found out my mistake : the basic contraint CA:TRUE is not only to be applied to the root certificate, but to all the intermediate ones.
So, the correct test is if i < nb-1 : (instead of if is_root :).
Add if I want to be as must restrictive as possible about the path length, I have to set it to nb-i-2.
And by the way, for my need, all other extensions are optional.

Using python print() with a bzip2/gzip2/etc stream

I've read the documentation on how to write strings into a compressed python file:
with bz2.open ( "/tmp/test.bz2", "w" ) as f:
f.write ( b"Hello" )
The problem I have is that I've functions accepting a file parameter, which is passed to the print() function, ie:
def produce_out ( out = sys.stdout ):
# many print ( file = out )
# invocations of other functions accepting out
Clearly, the cleanest and most modular way to obtain that my output is printed and compressed at the same time would be chaining the two above, ie:
with bz2.open ( "/tmp/test.bz2", "w" ) as f:
out = compressed_stream_adapter ( f )
produce_out ( out )
where compressed_stream_adapter() yields some object compatible with the file parameter that print() accepts and which automatically forwards the strings it receives to the compressed stream. This is how the compression works in Java, or how you can use the pipe operator in Linux shells to compress any kind of output (which also parallelises its endpoints, but that's not very important here).
My question is: does anything like compressed_stream_adapter() exist in python? Is there a different way to do it that does not require to change existing code?
Note that I already know I could do: out = io.StringIO () and later:
f.write ( out.getvalue ().encode () ). However, that's not good when I have to dynamically dump big amounts of data to files (which indeed, is why I want to compress them).
Answering myself: I guess there isn't any off-the-shelf way to do that.
So, I've followed the Dan Mašek comments and implemented a little wrapper, which relies on the fact that print() expects an object having a write method:
class BinaryWriter:
def __init__ ( self, bin_out, encoding = "utf-8", errors = 'strict' ):
self.bin_out = bin_out
self.encoding = encoding
self.errors = errors
def write ( self, s: str ):
self.bin_out.write ( s.encode ( self.encoding, self.errors ) )
def close ( self ):
self.bin_out.close ()
Usage:
with bz2.open ( file_path, "w" ) as bout
out = BinaryWriter ( bout )
print ( "Hello, world", file = out )
my_output ( out ) # Uses print( ..., file = out )
If compression is optional:
out = open ( file_path, mode = "w" ) if not file_path.endswith ( ".bz2" ) \
else BinaryWriter ( bz2.open ( file_path, "w" ) )
try:
my_output ( out )
finally:
out.close ()

Save my own topology:Mininet

I'm a newer in Mininet, I started my topology with CLI command: "sudo mn", after that, I'm adding some hosts and switches... but I want to save it for the next time.
How can I do it?
Example:
http://i1360.photobucket.com/albums/r653/HKati/Capture%20drsquoeacutecran%202016-04-23%20agrave%2007.08.02_zpsxcmh4u6s.png
I'm not sure if I got your question correctly but you can define your topology within a script:
Example my_topology.py
from mininet.topo import Topo
class MyTopo( Topo ):
def __init__( self ):
Topo.__init__( self )
# Add hosts and switches
left_host = self.addHost( 'h1' )
right_host = self.addHost( 'h2' )
left_switch = self.addSwitch( 's0' )
right_switch = self.addSwitch( 's2' )
# Add links
self.addLink( leftHost, left_switch, bw=10, delay='10ms', loss=0, max_queue_size=1000 )
self.addLink( left_switch, right_switch, bw=10, delay='10ms', loss=0, max_queue_size=1000 )
self.addLink( right_switch, rightHost, bw=10, delay='10ms', loss=0, max_queue_size=1000 )
topos = { 'mytopo': ( lambda: MyTopo() ) }
Then you can start it with
mn --custom my_topology.py --topo mytopo --link tc,bw=10,delay=10ms

Python IRC/Skype Bridge spamming messages

I've tried so many ways the past week or so to try to get this to work.
I've managed to get Skype2IRC to work in another script, and not spam IRC or anything. It was good. Just on message status, send message to IRC. That part I can get down easily. However, the part going from IRC to Skype is where I'm having issues. First, I figured I'd try to get it to work with multi-threading. Didn't go out well. Then, I tried this;
import os,sys,time,Skype4Py,socket,re,string
from random import choice
s = Skype4Py.Skype()
s.Attach() #Attach to Skype. Make sure to accept permissions from Skype client!
name = "Ibex"
network = "irc.myserver.net"
channel = "#Skype"
port = 6667
irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
irc.connect ( ( network, port ) )
print irc.recv ( 4096 )
irc.send ( 'NICK '+name+'\r\n' )
irc.send ( 'USER '+name+' '+name+' '+name+' : IRC Bot\r\n' )
irc.send ( 'JOIN '+channel+'\r\n' )
ircusername = '' #referencing variable so it can be used before, data will change in while loop
ircmessage = '' #same as above
def Ibex(Message, Status):
chat = Message.Chat
members = chat.MemberObjects
msg = Message.Body
send = Message.Chat.SendMessage
sAlias = Message.FromDisplayName
sUsername = Message.FromHandle
if Status == 'RECEIVED':
irc.send ( 'PRIVMSG '+channel+' :<Skype - '+sUsername+'>: '+msg+'\r\n' )
if ircusername != '':
try:
ircmessage = data.split(channel+" :",1)[1]
send("<IRC - "+ircusername+">: "+ircmessage)
except:
print "Error getting new IRC message."
s.OnMessageStatus = Ibex
while True:
data = irc.recv ( 4096 )
print data
if data.find ( 'PING' ) != -1:
irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
if data.find ( 'KICK' ) != -1:
irc.send ( 'JOIN '+channel+'\r\n' )
try:
ircusername = re.search(':(.*)!', data)
ircusername = ircusername.group(1)
except:
pass
After tons of trial and error. And, a LOT of spam in IRC and Skype, I managed to get this to send IRC messages to skype.
HOWEVER, it spams.
I'll send a message in IRC, and nothing will happen.
I'll send a message in Skype (hence s.OnMessageStatus = Ibex) and it sends the IRC message, as expected. However, it won't stop sending it. It spams it like crazy. I tried doing something like setting a sendMSG = True when a message is received, and setting sendMSG to false after sending it, then if sendMSG = true, then send. That didn't seem to work out well.
Anyone have any suggestions? Am I just missing something small causing this error? Thanks to anyone in advanced, this has been bothering me for a while now.
I managed to get an old IRC/Skype bridge to work a while ago, but that script is long gone and I can't remember exactly how I did it.

Categories