例如,我可以这样做:
if ($my_array = wp_get_category($id)) {
echo "asdf";
} else {
echo "1234";
}
Run Code Online (Sandbox Code Playgroud)
如果函数没有返回任何内容,我想进入else语句.
我正在尝试在我的网站上设置事件跟踪,但无法使其正常工作.
我的跟踪代码:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-420xxxxxxx', 'mywebsite.org');
ga('send', 'pageview');
</script>
Run Code Online (Sandbox Code Playgroud)
我的事件跟踪代码:
<a href="#PurchasePanelLink" class="uk-button uk-button-primary" onClick="$('#PurchasePanel').show(); _gaq.push(['_trackEvent', 'Button', 'Click', 'Purchase Details',, false]);">Purchase Details</a>
Run Code Online (Sandbox Code Playgroud) 我正在尝试在Django中设置一个表单并将数据保存到我的数据库,而不使用ModelForm.我的表单正在运行,但我坚持的部分是如何处理表单数据并将其保存在视图中.正如你所看到的,在'if form.is_valid()之后:'我陷入困境,无法想到正确的代码.
# models.py
from django.db import models
class Listing(models.Model):
business_name = models.CharField(max_length=80)
business_email = models.EmailField()
business_website = models.CharField(max_length=80)
business_phone = models.CharField(max_length=80)
# forms.py
from django import forms
class NewBusinessForm(forms.Form):
business_name = forms.CharField(label='Business Name', max_length=100)
business_phone = forms.CharField(label='Phone Number', max_length=100)
business_email = forms.EmailField(label='Email Address', max_length=100)
business_website = forms.CharField(label='Web Site', max_length=100)
# views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NewBusinessForm
def new_business(request):
if request.method == 'POST':
form = NewBusinessForm(request.POST)
if form.is_valid():
# process form data
return …Run Code Online (Sandbox Code Playgroud) 您是否设置外键就nullable=false好像总是期望数据库中该列上的外键一样?
我正在使用 sqlalchemy 并使用所需的外键设置我的模型。这有时会导致我session.commit()更频繁地运行,因为我需要父模型具有 id 并完全创建,以便在 ORM 中构建子对象。什么被认为是最佳实践?我的模型如下:
class Location(Base):
__tablename__ = 'locations'
id = Column(Integer, primary_key=True)
city = Column(String(50), nullable=False, unique=True)
hotels = relationship('Hotel', back_populates='location')
class Hotel(Base):
__tablename__ = 'hotels'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False, unique=True)
phone_number = Column(String(20))
parking_fee = Column(String(10))
location_id = Column(Integer, ForeignKey('locations.id'), nullable=False)
location = relationship('Location', back_populates='hotels')
Run Code Online (Sandbox Code Playgroud) 我正在尝试将以下 URL 结构提供给请求:
https://inventory.data.gov/api/action/datastore_search?resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&filters={"City":"Las Vegas","State":"NV"}
Run Code Online (Sandbox Code Playgroud)
我想将 URL 分解为参数,但我很难让过滤器部分正常工作。我最终使用了以下代码:
url = 'https://inventory.data.gov/api/action/datastore_search?' \
'resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&' \
'filters={"City":"' + city + '","State":"' + state + '"}'
resp = requests.get(url=url)
print resp.url
Run Code Online (Sandbox Code Playgroud)
有谁知道我如何修改它以处理类似的请求requests.get(url=url, params=params)?
我有一个Django应用程序并在Heroku上运行.我想运行一个名为import.py的简单脚本,它将CSV文件导入到我的模型中.它在我的本地计算机上运行良好.当我尝试使用此命令在Heroku上运行脚本时:
heroku run python manage.py < import.py
Run Code Online (Sandbox Code Playgroud)
它只是将脚本读回给我,但不执行任何内容.我究竟做错了什么?
编辑:
这是我运行时获得的结果的开始:heroku运行python manage.py <import.py
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import csv
>>> from bah_api.models import withDependents, withOutDependents, ZipMHA
>>>
>>> # Populate CSV file into model
>>> def LoadCSV(file_location, my_model, delim):
... f = open(file_location)
File "<console>", line 2
f = open(file_location)
^
IndentationError: expected an indented block
>>> csv_f = csv.reader(f, delimiter=delim)
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的Flask视图函数中模拟SendGrid方法,以便它在测试期间不发送电子邮件.当我运行下面的代码时,我得到一个错误'ImportError:没有名为sg的模块'.如何正确配置'sg'方法,以便在测试中找到它?
# test_helpers.py
from unittest import TestCase
from views import app
class PhotogTestCase(TestCase):
def setUp(self):
app.config['WTF_CSRF_ENABLED'] = False
app.config['TESTING'] = True
self.app = app
self.client = app.test_client()
# test_views.py
import mock
from test_helpers import PhotogTestCase
import sendgrid
class TestAddUser(PhotogTestCase):
sg = sendgrid.SendGridClient(app.config['SENDGRID_API_KEY'])
@mock.patch('sg.send')
def test_add_user_page_loads(self, mocked_send):
mocked_send.return_value = None # Do nothing on send
resp = self.client.post('/add_user', data={
'email': 'joe@hotmail.com'
}, follow_redirects=True)
assert 'Wow' in resp.data
# views.py
import sendgrid
from itsdangerous import URLSafeTimedSerializer
from flask import Flask, redirect, render_template, …Run Code Online (Sandbox Code Playgroud) 如何使用CSS填写UTF-8星的背景颜色(☆)?我尝试使用它,但它只更改边框颜色:
.rating {
color: #f70;
}Run Code Online (Sandbox Code Playgroud)
<p class="rating">☆☆☆☆</p>Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个递归函数,它接受一个JSON字典并将任何带有键名'rate'的值存储到列表中.然后,我将获取该列表并找到最低值.我的代码现在看起来像这样,但是在列表中生成多个空列表.
def recurse_keys(df):
rates = []
for key, value in df.items():
if key == 'rate':
rates.append(value)
if isinstance(df[key], dict):
recurse_keys(df[key])
Run Code Online (Sandbox Code Playgroud) 所有,
我有两个看起来像这样的选择:
<select name='input_34' id='input_1_34' class='small gfield_select' tabindex='1' >
<option value='29' >Alabama</option>
<option value='34' >Alaska</option>
<option value='42' >Arizona</option>
....
<select name='input_13' id='input_13' class='small gfield_select' tabindex="2">
<option value='-1' selected='selected'>Select a base</option>
<option class="level-0" value="29">Alabama</option>
<option class="level-1" value="30"> Anniston Army Depot</option>
<option class="level-1" value="333"> Fort Rucker</option>
<option class="level-1" value="32"> Maxwell-Gunter AFB</option>
<option class="level-1" value="33"> Redstone Arsenal</option>
<option class="level-0" value="34">Alaska</option>
<option class="level-1" value="35"> Eielson AFB</option>
<option class="level-1" value="36"> Elmendorf AFB</option>
<option class="level-1" value="37"> Fort Greely</option>
<option class="level-1" value="38"> Fort Richardson</option>
<option class="level-1" value="39"> Fort Wainwright</option>
<option class="level-1" value="40"> USCG ISC Kodiak</option>
<option class="level-1" …Run Code Online (Sandbox Code Playgroud) python ×5
django ×2
css ×1
css-shapes ×1
flask ×1
foreign-keys ×1
forms ×1
heroku ×1
if-statement ×1
jquery ×1
mocking ×1
options ×1
php ×1
recursion ×1
select ×1
sqlalchemy ×1
unit-testing ×1